From eee665926aa4ecdeaeae8402fabdc29dff9bb66a Mon Sep 17 00:00:00 2001 From: bootx Date: Tue, 8 Oct 2024 22:36:13 +0800 Subject: [PATCH] =?UTF-8?q?feat=20=E9=9B=86=E6=88=90=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E6=94=AF=E4=BB=98SDK=E4=BB=A3=E7=A0=81=E7=BB=93=E6=9E=84?= =?UTF-8?q?=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- .../auth/handler/LoginSuccessHandlerImpl.java | 2 +- .../quartz/handler/JobLogAspectHandler.java | 2 +- .../channel/union/code/UnionPayCode.java | 65 + .../union/sdk/api/UnionPayConfigStorage.java | 25 - .../channel/union/sdk/api/UnionPayKit.java | 56 +- .../union/sdk/api/UnionPayService.java | 46 +- .../channel/union/sdk/bean/UnionPayOrder.java | 12 + .../union/sdk/bean/UnionRefundOrder.java | 12 + .../service/config/UnionPayConfigService.java | 14 +- .../union/service/pay/UnionPayService.java | 181 ++ .../reconcile/UnionPayReconcileService.java | 17 + .../service/refund/UnionPayRefundService.java | 48 + .../service/sync/UnionPaySyncService.java | 17 + .../strategy/UnionPayReconcileStrategy.java | 40 + .../union/strategy/UnionPayStrategy.java | 78 + .../union/strategy/UnionRefundStrategy.java | 59 + .../union/strategy/UnionSyncPayStrategy.java | 31 + .../strategy/UnionSyncRefundStrategy.java | 30 + .../org/dromara/daxpay/core/util/PayUtil.java | 9 - daxpay-single/daxpay-single-unisdk/pom.xml | 29 + .../common/api/BasePayConfigStorage.java | 113 +- .../unisdk/common/api/BasePayService.java | 202 +- .../common/api/DefaultPayMessageHandler.java | 6 +- .../unisdk/common/api/PayConfigStorage.java | 10 - .../unisdk/common/api/PayMessageRouter.java | 86 +- .../common/api/PayMessageRouterRule.java | 111 +- .../daxpay/unisdk/common/api/PayService.java | 172 -- .../unisdk/common/bean/AssistOrder.java | 81 +- .../unisdk/common/bean/BaseRefundResult.java | 7 +- .../unisdk/common/bean/CertStoreType.java | 4 +- .../daxpay/unisdk/common/bean/CloseOrder.java | 14 - .../common/bean/DefaultCountryCode.java | 2 +- .../unisdk/common/bean/DefaultCurType.java | 2 +- .../common/bean/DefaultNoticeRequest.java | 2 +- .../unisdk/common/bean/NoticeParams.java | 40 +- .../daxpay/unisdk/common/bean/PayMessage.java | 46 +- .../daxpay/unisdk/common/bean/PayOrder.java | 149 +- .../unisdk/common/bean/PayOutMessage.java | 12 +- .../unisdk/common/bean/RefundOrder.java | 68 +- .../unisdk/common/bean/TransferOrder.java | 143 +- .../common/bean/outbuilder/JsonBuilder.java | 6 +- .../bean/outbuilder/PayXmlOutMessage.java | 12 +- .../common/bean/result/PayException.java | 4 +- .../unisdk/common/http/ClientHttpRequest.java | 118 +- .../unisdk/common/http/HttpConfigStorage.java | 159 +- .../daxpay/unisdk/common/http/HttpHeader.java | 32 +- .../common/http/HttpRequestTemplate.java | 52 +- .../unisdk/common/http/HttpStringEntity.java | 32 +- .../unisdk/common/http/ResponseEntity.java | 13 +- .../unisdk/common/http/UriVariables.java | 11 +- .../daxpay/unisdk/common/util/DateUtils.java | 7 +- .../daxpay/unisdk/common/util/IOUtils.java | 2385 ----------------- .../common/util/LogExceptionHandler.java | 7 +- .../daxpay/unisdk/common/util/MapGen.java | 40 - .../common/util/MatrixToImageWriter.java | 136 - .../daxpay/unisdk/common/util/Util.java | 68 +- .../daxpay/unisdk/common/util/XML.java | 6 +- .../common/util/sign/CertDescriptor.java | 91 +- .../common/util/sign/SignTextUtils.java | 21 +- .../unisdk/common/util/sign/SignUtils.java | 17 - .../unisdk/common/util/sign/encrypt/AES.java | 73 - .../common/util/sign/encrypt/HmacSha256.java | 14 +- .../unisdk/common/util/sign/encrypt/RSA.java | 42 +- .../common/util/sign/encrypt/sm3/SM3.java | 25 +- .../unisdk/common/util/str/StringUtils.java | 6 +- 66 files changed, 1130 insertions(+), 4292 deletions(-) create mode 100644 daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/bean/UnionPayOrder.java create mode 100644 daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/bean/UnionRefundOrder.java create mode 100644 daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/pay/UnionPayService.java create mode 100644 daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/reconcile/UnionPayReconcileService.java create mode 100644 daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/refund/UnionPayRefundService.java create mode 100644 daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/sync/UnionPaySyncService.java create mode 100644 daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionPayReconcileStrategy.java create mode 100644 daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionPayStrategy.java create mode 100644 daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionRefundStrategy.java create mode 100644 daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionSyncPayStrategy.java create mode 100644 daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionSyncRefundStrategy.java delete mode 100644 daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/CloseOrder.java delete mode 100644 daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/IOUtils.java delete mode 100644 daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/MapGen.java delete mode 100644 daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/MatrixToImageWriter.java delete mode 100644 daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/AES.java diff --git a/README.md b/README.md index 0d2d09ffd..e60f915c2 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,7 @@ public class PayOrderTest { [**当前开发进度和任务池**](/_doc/Task.md) -[**历史更新记录**](/_doc/ChangeLog.md) +[**历史更新记录**](/_doc/Changelog.md) ## 🥪 关于我们 diff --git a/bootx-platform/bootx-platform-service/service-iam/src/main/java/cn/bootx/platform/iam/auth/handler/LoginSuccessHandlerImpl.java b/bootx-platform/bootx-platform-service/service-iam/src/main/java/cn/bootx/platform/iam/auth/handler/LoginSuccessHandlerImpl.java index 1375bc4b0..d360846be 100644 --- a/bootx-platform/bootx-platform-service/service-iam/src/main/java/cn/bootx/platform/iam/auth/handler/LoginSuccessHandlerImpl.java +++ b/bootx-platform/bootx-platform-service/service-iam/src/main/java/cn/bootx/platform/iam/auth/handler/LoginSuccessHandlerImpl.java @@ -56,7 +56,7 @@ public class LoginSuccessHandlerImpl implements LoginSuccessHandler { .setBrowser(userAgent.getBrowser().getName() + " " + userAgent.getVersion()) .setLoginTime(LocalDateTime.now()); loginLogService.add(loginLog); -// userExpandInfoService.updateLoginTime(loginLog.getUserId()); +// userExpandInfoService.updateLoginTime(loginlog.getUserId()); } } diff --git a/bootx-platform/bootx-platform-starter/starter-quartz/src/main/java/cn/bootx/platform/starter/quartz/handler/JobLogAspectHandler.java b/bootx-platform/bootx-platform-starter/starter-quartz/src/main/java/cn/bootx/platform/starter/quartz/handler/JobLogAspectHandler.java index e42652636..015410a4b 100644 --- a/bootx-platform/bootx-platform-starter/starter-quartz/src/main/java/cn/bootx/platform/starter/quartz/handler/JobLogAspectHandler.java +++ b/bootx-platform/bootx-platform-starter/starter-quartz/src/main/java/cn/bootx/platform/starter/quartz/handler/JobLogAspectHandler.java @@ -40,7 +40,7 @@ public class JobLogAspectHandler { @Around("logPointCut()") public Object doAfterReturning(ProceedingJoinPoint pjp) throws Throwable { // Class clazz = pjp.getTarget().getClass(); -// JobLog jobLog = clazz.getAnnotation(JobLog.class); +// JobLog jobLog = clazz.getAnnotation(Joblog.class); // LocalDateTime start = LocalDateTime.now(); // try { Object result = pjp.proceed(); diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/code/UnionPayCode.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/code/UnionPayCode.java index a4e6174a0..3d2acc08f 100644 --- a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/code/UnionPayCode.java +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/code/UnionPayCode.java @@ -1,5 +1,7 @@ package org.dromara.daxpay.channel.union.code; +import org.dromara.daxpay.channel.union.sdk.bean.SDKConstants; + /** * 云闪付常量编码 * @author xxm @@ -7,6 +9,69 @@ package org.dromara.daxpay.channel.union.code; */ public interface UnionPayCode { + /** 应答码 00表示成功 */ + String RESP_CODE = SDKConstants.param_respCode; + + /** 原交易应答码 00表示成功 */ + String RESP_ORIG_CODE = SDKConstants.param_origRespCode; + + /** 应答码信息 */ + String RESP_MSG = SDKConstants.param_respMsg; + + /** 业务结果 00表示成功 */ + String RESP_SUCCESS = SDKConstants.OK_RESP_CODE; + + /** 交易类型 */ + String TXN_TYPE = "txnType"; + + /** 网关订单号 */ + String QUERY_ID = "queryId"; + + /** 第三方订单号(本地订单号) */ + String ORDER_ID = "orderId"; + + /** APP支付 银联订单号 */ + String PAY_APP_TN = SDKConstants.param_tn; + + /** 交易类型 支付 */ + String TXN_TYPE_PAY = "01"; + + /** 交易类型 退款 */ + String TXN_TYPE_REFUND = "04"; + + /** + * 订单发送时间 + * 格式: yyyyMMddHHmmss + */ + String TXN_TIME = "txnTime"; + + + /** 退款金额 */ + String TXN_AMT = "txnAmt"; + + /** 总金额 */ + String TOTAL_FEE = "settleAmt"; + + /** 对账单下载类型编码 */ + String RECONCILE_BILL_TYPE = "00"; + + /** 文件内容 */ + String FILE_CONTENT = "fileContent"; + + /** 明细对账单文件前缀 */ + String RECONCILE_FILE_PREFIX = "INN"; + + /* 对账单交易代码 */ + /** 消费 */ + String RECONCILE_TYPE_PAY = "S22"; + + /** 退款 */ + String RECONCILE_TYPE_REFUND = "S30 "; + + + /** 对账各字段位数游标 */ + int[] RECONCILE_BILL_SPLIT = {3,11,11,6,10,19,12,4,2,21,2,32,2,6,10,13,13,4,15,2,2,6,2,4,32,1,21,15,1,15,32,13,13,8,32,13,13,12,2,1,32,13,2,1,12,67}; + /** * 签名类型 */ diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/api/UnionPayConfigStorage.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/api/UnionPayConfigStorage.java index b22fd0cb3..9e98c3f78 100644 --- a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/api/UnionPayConfigStorage.java +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/api/UnionPayConfigStorage.java @@ -149,11 +149,6 @@ public class UnionPayConfigStorage extends BasePayConfigStorage { this.keyPrivateCertPwd = keyPrivateCertPwd; } - @Override - public String getAppid() { - return null; - } - /** * 应用id * 纠正名称 @@ -165,26 +160,6 @@ public class UnionPayConfigStorage extends BasePayConfigStorage { return null; } - /** - * @return 合作者id - * @see #getPid() - */ - @Deprecated - public String getPartner() { - return merId; - } - - - /** - * 设置合作者id - * - * @param partner 合作者id - * @see #setPid(String) - */ - @Deprecated - public void setPartner(String partner) { - this.merId = partner; - } @Override public String getPid() { diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/api/UnionPayKit.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/api/UnionPayKit.java index 51156da48..d0212c7b6 100644 --- a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/api/UnionPayKit.java +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/api/UnionPayKit.java @@ -1,6 +1,8 @@ package org.dromara.daxpay.channel.union.sdk.api; +import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSONObject; +import lombok.extern.slf4j.Slf4j; import org.dromara.daxpay.channel.union.sdk.bean.*; import org.dromara.daxpay.unisdk.common.bean.*; import org.dromara.daxpay.unisdk.common.bean.outbuilder.PayTextOutMessage; @@ -30,6 +32,7 @@ import java.util.*; * @author xxm * @since 2024/3/8 */ +@Slf4j public class UnionPayKit extends UnionPayService { /** * 测试域名 @@ -90,7 +93,7 @@ public class UnionPayKit extends UnionPayService { certDescriptor.initRootCert(payConfigStorage.getAcpRootCertInputStream()); } catch (IOException e) { - LOG.error("", e); + log.error("", e); } @@ -182,18 +185,6 @@ public class UnionPayKit extends UnionPayService { } - /** - * 回调校验 - * - * @param result 回调回来的参数集 - * @return 签名校验 true通过 - */ - @Deprecated - @Override - public boolean verify(Map result) { - return verify(new NoticeParams(result)); - } - /** * 回调校验 * @@ -204,7 +195,7 @@ public class UnionPayKit extends UnionPayService { public boolean verify(NoticeParams noticeParams) { final Map result = noticeParams.getBody(); if (null == result || result.get(SDKConstants.param_signature) == null) { - LOG.debug("银联支付验签异常:params:" + result); + log.debug("银联支付验签异常:params:" + result); return false; } return this.signVerify(result, (String) result.get(SDKConstants.param_signature)); @@ -275,7 +266,7 @@ public class UnionPayKit extends UnionPayService { params.put(SDKConstants.param_orderId, order.getOutTradeNo()); - if (StringUtils.isNotEmpty(order.getAddition())) { + if (StrUtil.isNotEmpty(order.getAddition())) { params.put(SDKConstants.param_reqReserved, order.getAddition()); } switch (type) { @@ -303,7 +294,6 @@ public class UnionPayKit extends UnionPayService { params.put("orderDesc", order.getSubject()); } params.putAll(order.getAttrs()); - params = preOrderHandler(params, order); return setSign(params); } @@ -384,10 +374,10 @@ public class UnionPayKit extends UnionPayService { return cert; } catch (CertPathBuilderException e) { - LOG.error("verify certificate chain fail.", e); + log.error("verify certificate chain fail.", e); } catch (GeneralSecurityException e) { - LOG.error("", e); + log.error("", e); } return null; } @@ -432,7 +422,7 @@ public class UnionPayKit extends UnionPayService { public String getQrPay(PayOrder order) { order.setTransactionType(UnionTransactionType.APPLY_QR_CODE); JSONObject response = postOrder(order, getBackTransUrl()); - if (this.verify(response)) { + if (this.verify(new NoticeParams(response))) { if (SDKConstants.OK_RESP_CODE.equals(response.get(SDKConstants.param_respCode))) { //成功 return (String) response.get(SDKConstants.param_qrCode); @@ -545,7 +535,7 @@ public class UnionPayKit extends UnionPayService { order.setTransactionType(UnionTransactionType.APP); } JSONObject response = postOrder(order, getAppTransUrl()); - if (this.verify(response)) { + if (this.verify(new NoticeParams(response))) { if (SDKConstants.OK_RESP_CODE.equals(response.get(SDKConstants.param_respCode))) { // //成功,获取tn号 // String tn = (String)response.get(SDKConstants.param_tn); @@ -556,19 +546,6 @@ public class UnionPayKit extends UnionPayService { throw new PayErrorException(new PayException("failure", "验证签名失败", response.toJSONString())); } - /** - * 交易查询接口 - * - * @param tradeNo 支付平台订单号 - * @param outTradeNo 商户单号 - * @return 返回查询回来的结果集,支付方原值返回 - */ - @Override - public Map query(String tradeNo, String outTradeNo) { - return query(new AssistOrder(tradeNo, outTradeNo)); - - } - /** * 交易查询接口 * @@ -629,19 +606,6 @@ public class UnionPayKit extends UnionPayService { throw new PayErrorException(new PayException("failure", "验证签名失败", response.toJSONString())); } - /** - * 交易关闭接口 - * 使用冲正接口 - * - * @param tradeNo 支付平台订单号 - * @param outTradeNo 商户单号 - * @return 返回支付方交易关闭后的结果 - */ - @Override - public Map close(String tradeNo, String outTradeNo) { - return Collections.emptyMap(); - } - /** * 交易关闭接口 * TODO 这个是冲正接口, 后续进行迁移 diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/api/UnionPayService.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/api/UnionPayService.java index 679eaff7f..e34a1079d 100644 --- a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/api/UnionPayService.java +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/api/UnionPayService.java @@ -184,20 +184,6 @@ public class UnionPayService extends BasePayService { } - /** - * 回调校验 - * - * @param result 回调回来的参数集 - * @return 签名校验 true通过 - */ - @Deprecated - @Override - public boolean verify(Map result) { - - - return verify(new NoticeParams(result)); - } - /** * 回调校验 * @@ -309,7 +295,6 @@ public class UnionPayService extends BasePayService { params.put("orderDesc", order.getSubject()); } params.putAll(order.getAttrs()); - params = preOrderHandler(params, order); return setSign(params); } @@ -441,7 +426,7 @@ public class UnionPayService extends BasePayService { public String getQrPay(PayOrder order) { order.setTransactionType(UnionTransactionType.APPLY_QR_CODE); JSONObject response = postOrder(order, getBackTransUrl()); - if (this.verify(response)) { + if (this.verify(new NoticeParams(response))) { if (SDKConstants.OK_RESP_CODE.equals(response.get(SDKConstants.param_respCode))) { //成功 return (String) response.get(SDKConstants.param_qrCode); @@ -550,7 +535,7 @@ public class UnionPayService extends BasePayService { order.setTransactionType(UnionTransactionType.APP); } JSONObject response = postOrder(order, getAppTransUrl()); - if (this.verify(response)) { + if (this.verify(new NoticeParams(response))) { if (SDKConstants.OK_RESP_CODE.equals(response.get(SDKConstants.param_respCode))) { // //成功,获取tn号 // String tn = (String)response.get(SDKConstants.param_tn); @@ -562,19 +547,6 @@ public class UnionPayService extends BasePayService { throw new PayErrorException(new PayException("failure", "验证签名失败", response.toJSONString())); } - /** - * 交易查询接口 - * - * @param tradeNo 支付平台订单号 - * @param outTradeNo 商户单号 - * @return 返回查询回来的结果集,支付方原值返回 - */ - @Override - public Map query(String tradeNo, String outTradeNo) { - return query(new AssistOrder(tradeNo, outTradeNo)); - - } - /** * 交易查询接口 * @@ -646,18 +618,6 @@ public class UnionPayService extends BasePayService { throw new PayErrorException(new PayException("failure", "验证签名失败", response.toJSONString())); } - /** - * 交易关闭接口 - * - * @param tradeNo 支付平台订单号 - * @param outTradeNo 商户单号 - * @return 返回支付方交易关闭后的结果 - */ - @Override - public Map close(String tradeNo, String outTradeNo) { - return Collections.emptyMap(); - } - /** * 交易关闭接口 * @@ -718,7 +678,7 @@ public class UnionPayService extends BasePayService { this.setSign(params); String responseStr = getHttpRequestTemplate().postForObject(this.getFileTransUrl(), params, String.class); JSONObject response = UriVariables.getParametersToMap(responseStr); - if (this.verify(response)) { + if (this.verify(new NoticeParams(response))) { if (SDKConstants.OK_RESP_CODE.equals(response.get(SDKConstants.param_respCode))) { return response; diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/bean/UnionPayOrder.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/bean/UnionPayOrder.java new file mode 100644 index 000000000..ca95a3cdf --- /dev/null +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/bean/UnionPayOrder.java @@ -0,0 +1,12 @@ +package org.dromara.daxpay.channel.union.sdk.bean; + + +import org.dromara.daxpay.unisdk.common.bean.PayOrder; + +/** + * 继承SDK中的类, 防止与系统中的类名称冲突 + * @author xxm + * @since 2024/3/8 + */ +public class UnionPayOrder extends PayOrder { +} diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/bean/UnionRefundOrder.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/bean/UnionRefundOrder.java new file mode 100644 index 000000000..2685c3b35 --- /dev/null +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/sdk/bean/UnionRefundOrder.java @@ -0,0 +1,12 @@ +package org.dromara.daxpay.channel.union.sdk.bean; + + +import org.dromara.daxpay.unisdk.common.bean.RefundOrder; + +/** + * 继承SDK中的类, 防止与系统中的类名称冲突 + * @author xxm + * @since 2024/3/8 + */ +public class UnionRefundOrder extends RefundOrder { +} diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/config/UnionPayConfigService.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/config/UnionPayConfigService.java index f6d597c05..e02bef550 100644 --- a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/config/UnionPayConfigService.java +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/config/UnionPayConfigService.java @@ -14,6 +14,7 @@ import org.dromara.daxpay.channel.union.result.UnionPayConfigResult; import org.dromara.daxpay.channel.union.sdk.api.UnionPayConfigStorage; import org.dromara.daxpay.channel.union.sdk.api.UnionPayKit; import org.dromara.daxpay.core.enums.ChannelEnum; +import org.dromara.daxpay.core.exception.ChannelNotEnableException; import org.dromara.daxpay.core.exception.ConfigNotEnableException; import org.dromara.daxpay.core.exception.DataErrorException; import org.dromara.daxpay.service.common.cache.ChannelConfigCacheService; @@ -95,7 +96,18 @@ public class UnionPayConfigService { } /** - * 获取支付宝支付配置 + * 获取并检查支付配置 + */ + public UnionPayConfig getAndCheckConfig() { + UnionPayConfig unionPayConfig = this.getUnionPayConfig(); + if (!unionPayConfig.getEnable()){ + throw new ChannelNotEnableException("云闪付支付未启用"); + } + return unionPayConfig; + } + + /** + * 获取云闪付支付配置 */ public UnionPayConfig getUnionPayConfig(){ MchAppLocal mchAppInfo = PaymentContextLocal.get().getMchAppInfo(); diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/pay/UnionPayService.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/pay/UnionPayService.java new file mode 100644 index 000000000..384a51889 --- /dev/null +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/pay/UnionPayService.java @@ -0,0 +1,181 @@ +package org.dromara.daxpay.channel.union.service.pay; + +import cn.bootx.platform.core.exception.ValidationFailedException; +import cn.bootx.platform.core.util.BigDecimalUtil; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.map.MapUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.dromara.daxpay.channel.union.code.UnionPayCode; +import org.dromara.daxpay.channel.union.entity.config.UnionPayConfig; +import org.dromara.daxpay.channel.union.param.pay.UnionPayParam; +import org.dromara.daxpay.channel.union.sdk.api.UnionPayKit; +import org.dromara.daxpay.channel.union.sdk.bean.UnionPayOrder; +import org.dromara.daxpay.channel.union.sdk.bean.UnionTransactionType; +import org.dromara.daxpay.core.enums.PayMethodEnum; +import org.dromara.daxpay.core.exception.AmountExceedLimitException; +import org.dromara.daxpay.core.exception.TradeFailException; +import org.dromara.daxpay.core.param.trade.pay.PayParam; +import org.dromara.daxpay.service.bo.trade.PayResultBo; +import org.dromara.daxpay.service.entity.order.pay.PayOrder; +import org.dromara.daxpay.unisdk.common.bean.NoticeParams; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.util.Date; +import java.util.Map; +import java.util.Objects; + +/** + * 云闪付支付 + * @author xxm + * @since 2022/3/11 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class UnionPayService { + + /** + * 支付前检查支付方式是否可用 + */ + public void validation(PayParam payParam, UnionPayConfig unionPayConfig) { + + // 支付金额是否超限 + if (BigDecimalUtil.isGreaterThan(payParam.getAmount(),unionPayConfig.getLimitAmount())) { + throw new AmountExceedLimitException("微信支付金额超限"); + } + } + + /** + * 支付接口 + */ + public PayResultBo pay(PayOrder payOrder, UnionPayParam unionPayParam, UnionPayKit unionPayKit){ + BigDecimal totalFee = payOrder.getAmount(); + String payBody = null; + PayMethodEnum payMethodEnum = PayMethodEnum.findByCode(payOrder.getMethod()); + + // 二维码支付 + if (payMethodEnum == PayMethodEnum.QRCODE) { + payBody = this.qrCodePay(totalFee, payOrder, unionPayKit); + } + // 付款码支付 + else if (payMethodEnum == PayMethodEnum.BARCODE) { + this.barCodePay(totalFee, payOrder, unionPayParam.getAuthCode(), unionPayKit); + } + // APP支付 + else if (payMethodEnum == PayMethodEnum.APP) { + payBody = this.appPay(totalFee, payOrder, unionPayParam, unionPayKit); + } + // web支付 + else if (payMethodEnum == PayMethodEnum.WEB) { + payBody = this.formPay(totalFee, payOrder, unionPayKit, UnionTransactionType.WEB); + } + // wap支付 + else if (payMethodEnum == PayMethodEnum.WAP) { + payBody = this.formPay(totalFee, payOrder, unionPayKit, UnionTransactionType.WAP ); + } + + return new PayResultBo().setPayBody(payBody); + } + + /** + * jsapi支付 + */ + private String formPay(BigDecimal amount, PayOrder payOrder, UnionPayKit unionPayKit, UnionTransactionType type) { + Date expiredTime = DateUtil.date(payOrder.getExpiredTime()); + + UnionPayOrder unionPayOrder = new UnionPayOrder(); + unionPayOrder.setOutTradeNo(payOrder.getOrderNo()); + unionPayOrder.setSubject(payOrder.getTitle()); + unionPayOrder.setPrice(amount); + unionPayOrder.setExpirationTime(expiredTime); + unionPayOrder.setTransactionType(type); + return unionPayKit.toPay(unionPayOrder); + } + + /** + * jsapi支付 + */ + private String b2bPay(BigDecimal amount, PayOrder payOrder, UnionPayKit unionPayKit) { + Date expiredTime = DateUtil.date(payOrder.getExpiredTime()); + + UnionPayOrder unionPayOrder = new UnionPayOrder(); + unionPayOrder.setOutTradeNo(payOrder.getOrderNo()); + unionPayOrder.setSubject(payOrder.getTitle()); + unionPayOrder.setPrice(amount); + unionPayOrder.setExpirationTime(expiredTime); + unionPayOrder.setTransactionType(UnionTransactionType.B2B); + return unionPayKit.toPay(unionPayOrder); + } + + /** + * APP支付 + */ + private String appPay(BigDecimal amount, PayOrder payOrder, UnionPayParam unionPayParam, UnionPayKit unionPayKit) { + + Date expiredTime = DateUtil.date(payOrder.getExpiredTime()); + + + UnionPayOrder unionPayOrder = new UnionPayOrder(); + unionPayOrder.setOutTradeNo(payOrder.getOrderNo()); + unionPayOrder.setSubject(payOrder.getTitle()); + unionPayOrder.setPrice(amount); + unionPayOrder.setExpirationTime(expiredTime); + + Map result = unionPayKit.app(unionPayOrder); + String resultCode = MapUtil.getStr(result, UnionPayCode.RESP_CODE); + + // 支付失败 + if (!(Objects.equals(resultCode, UnionPayCode.RESP_SUCCESS))) { + log.warn("云闪付支付失败:{}", result); + String errMsg = MapUtil.getStr(result, UnionPayCode.RESP_MSG); + throw new TradeFailException(errMsg); + } + + return MapUtil.getStr(result, UnionPayCode.PAY_APP_TN); + } + + /** + * 扫码支付 + */ + private String qrCodePay(BigDecimal amount, PayOrder payOrder, UnionPayKit unionPayKit){ + Date expiredTime = DateUtil.date(payOrder.getExpiredTime()); + + UnionPayOrder unionPayOrder = new UnionPayOrder(); + unionPayOrder.setOutTradeNo(payOrder.getOrderNo()); + unionPayOrder.setSubject(payOrder.getTitle()); + unionPayOrder.setPrice(amount); + unionPayOrder.setExpirationTime(expiredTime); + return unionPayKit.getQrPay(unionPayOrder); + } + + /** + * 付款码支付 + */ + private void barCodePay(BigDecimal amount, PayOrder payOrder, String authCode, UnionPayKit unionPayKit) { + Date expiredTime = DateUtil.date(payOrder.getExpiredTime()); + + UnionPayOrder unionPayOrder = new UnionPayOrder(); + unionPayOrder.setAuthCode(authCode); + unionPayOrder.setOutTradeNo(payOrder.getOrderNo()); + unionPayOrder.setSubject(payOrder.getTitle()); + unionPayOrder.setPrice(amount); + unionPayOrder.setExpirationTime(expiredTime); + Map result = unionPayKit.microPay(unionPayOrder); + + if (!unionPayKit.verify(new NoticeParams(result))) { + log.warn("云闪付支付验签失败:{}", result); + throw new ValidationFailedException("云闪付支付验签失败"); + } + + String resultCode = MapUtil.getStr(result, UnionPayCode.RESP_CODE); + + // 支付失败 + if (!(Objects.equals(resultCode, UnionPayCode.RESP_SUCCESS))) { + log.warn("云闪付支付失败:{}", result); + String errMsg = MapUtil.getStr(result, UnionPayCode.RESP_MSG); + throw new TradeFailException(errMsg); + } + } +} diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/reconcile/UnionPayReconcileService.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/reconcile/UnionPayReconcileService.java new file mode 100644 index 000000000..a10e47c10 --- /dev/null +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/reconcile/UnionPayReconcileService.java @@ -0,0 +1,17 @@ +package org.dromara.daxpay.channel.union.service.reconcile; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +/** + * 云闪付对账 + * @author xxm + * @since 2024/3/7 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class UnionPayReconcileService { + +} diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/refund/UnionPayRefundService.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/refund/UnionPayRefundService.java new file mode 100644 index 000000000..4199e81b8 --- /dev/null +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/refund/UnionPayRefundService.java @@ -0,0 +1,48 @@ +package org.dromara.daxpay.channel.union.service.refund; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.dromara.daxpay.channel.union.code.UnionPayCode; +import org.dromara.daxpay.channel.union.sdk.api.UnionPayKit; +import org.dromara.daxpay.channel.union.sdk.bean.UnionRefundOrder; +import org.dromara.daxpay.channel.union.sdk.bean.UnionRefundResult; +import org.dromara.daxpay.core.enums.RefundStatusEnum; +import org.dromara.daxpay.service.bo.trade.RefundResultBo; +import org.dromara.daxpay.service.entity.order.refund.RefundOrder; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; + +/** + * 云闪付退款操作 + * @author xxm + * @since 2024/3/7 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class UnionPayRefundService { + + /** + * 退款方法 + */ + public RefundResultBo refund(RefundOrder refundOrder, UnionPayKit unionPayKit) { + + // 金额转换 + BigDecimal refundAmount = refundOrder.getAmount(); + BigDecimal orderAmount = refundOrder.getOrderAmount(); + + UnionRefundOrder unionRefundOrder = new UnionRefundOrder(); + unionRefundOrder.setRefundNo(refundOrder.getRefundNo()); + unionRefundOrder.setTradeNo(refundOrder.getOutOrderNo()); + unionRefundOrder.setRefundAmount(refundAmount); + unionRefundOrder.setTotalAmount(orderAmount); + UnionRefundResult refund = unionPayKit.refund(unionRefundOrder); + + String outRefundNo = (String) refund.getAttr(UnionPayCode.QUERY_ID); + // 云闪付退款是否成功需要查询状态, 所以设置为退款中状态 + return new RefundResultBo() + .setStatus(RefundStatusEnum.PROGRESS) + .setOutRefundNo(outRefundNo); + } +} diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/sync/UnionPaySyncService.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/sync/UnionPaySyncService.java new file mode 100644 index 000000000..314902a5c --- /dev/null +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/service/sync/UnionPaySyncService.java @@ -0,0 +1,17 @@ +package org.dromara.daxpay.channel.union.service.sync; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +/** + * 云闪付支付同步 + * @author xxm + * @since 2024/3/7 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class UnionPaySyncService { + +} diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionPayReconcileStrategy.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionPayReconcileStrategy.java new file mode 100644 index 000000000..61582cf22 --- /dev/null +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionPayReconcileStrategy.java @@ -0,0 +1,40 @@ +package org.dromara.daxpay.channel.union.strategy; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.dromara.daxpay.core.enums.ChannelEnum; +import org.dromara.daxpay.service.bo.reconcile.ReconcileResolveResultBo; +import org.dromara.daxpay.service.enums.ReconcileFileTypeEnum; +import org.dromara.daxpay.service.strategy.AbsReconcileStrategy; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE; + +/** + * 银联对账 + * @author xxm + * @since 2024/3/8 + */ +@Slf4j +@Service +@Scope(SCOPE_PROTOTYPE) +@RequiredArgsConstructor +public class UnionPayReconcileStrategy extends AbsReconcileStrategy { + + @Override + public ReconcileResolveResultBo uploadAndResolve(MultipartFile file, ReconcileFileTypeEnum fileType) { + return null; + } + + @Override + public ReconcileResolveResultBo downAndResolve() { + return null; + } + + @Override + public String getChannel() { + return ChannelEnum.UNION_PAY.getCode(); + } +} diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionPayStrategy.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionPayStrategy.java new file mode 100644 index 000000000..e0e78a611 --- /dev/null +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionPayStrategy.java @@ -0,0 +1,78 @@ +package org.dromara.daxpay.channel.union.strategy; + +import cn.bootx.platform.core.exception.ValidationFailedException; +import cn.bootx.platform.core.util.JsonUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.dromara.daxpay.channel.union.entity.config.UnionPayConfig; +import org.dromara.daxpay.channel.union.param.pay.UnionPayParam; +import org.dromara.daxpay.channel.union.sdk.api.UnionPayKit; +import org.dromara.daxpay.channel.union.service.config.UnionPayConfigService; +import org.dromara.daxpay.channel.union.service.pay.UnionPayService; +import org.dromara.daxpay.core.enums.ChannelEnum; +import org.dromara.daxpay.service.bo.trade.PayResultBo; +import org.dromara.daxpay.service.strategy.AbsPayStrategy; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Service; + +import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE; + +/** + * 云闪付 + * + * @author xxm + * @since 2022/3/8 + */ +@Slf4j +@Scope(SCOPE_PROTOTYPE) +@Service +@RequiredArgsConstructor +public class UnionPayStrategy extends AbsPayStrategy { + + private final UnionPayService unionPayService; + + private final UnionPayConfigService unionPayConfigService; + + private UnionPayParam unionPayParam; + + private UnionPayConfig unionPayConfig; + + @Override + public String getChannel() { + return ChannelEnum.UNION_PAY.getCode(); + } + /** + * 支付前操作 + */ + @Override + public void doBeforePayHandler() { + try { + // 云闪付参数验证 + var channelParam = this.getPayParam().getExtraParam(); + if (StrUtil.isNotBlank(channelParam)) { + this.unionPayParam = JsonUtil.toBean(channelParam, UnionPayParam.class); + } + else { + this.unionPayParam = new UnionPayParam(); + } + } + catch (JSONException e) { + throw new ValidationFailedException("支付参数错误"); + } + // 检查并获取云闪付支付配置 + this.unionPayConfig = unionPayConfigService.getAndCheckConfig(); + unionPayService.validation(this.getPayParam(), unionPayConfig); + } + + /** + * 发起支付操作 + */ + @Override + public PayResultBo doPayHandler() { + UnionPayKit unionPayKit = unionPayConfigService.initPayService(unionPayConfig); + return unionPayService.pay(this.getOrder(), this.unionPayParam, unionPayKit); + } +} + diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionRefundStrategy.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionRefundStrategy.java new file mode 100644 index 000000000..6df63af6f --- /dev/null +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionRefundStrategy.java @@ -0,0 +1,59 @@ +package org.dromara.daxpay.channel.union.strategy; + +import lombok.RequiredArgsConstructor; +import org.dromara.daxpay.channel.union.entity.config.UnionPayConfig; +import org.dromara.daxpay.channel.union.sdk.api.UnionPayKit; +import org.dromara.daxpay.channel.union.service.config.UnionPayConfigService; +import org.dromara.daxpay.channel.union.service.refund.UnionPayRefundService; +import org.dromara.daxpay.core.enums.ChannelEnum; +import org.dromara.daxpay.service.bo.trade.RefundResultBo; +import org.dromara.daxpay.service.strategy.AbsRefundStrategy; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE; + +/** + * 云闪付支付退款 + * @author xxm + * @since 2023/7/5 + */ +@Scope(SCOPE_PROTOTYPE) +@Component +@RequiredArgsConstructor +public class UnionRefundStrategy extends AbsRefundStrategy { + + private final UnionPayRefundService unionPayRefundService; + + private final UnionPayConfigService unionPayConfigService; + + private UnionPayConfig unionPayConfig; + + /** + * 策略标识 + * + * @see ChannelEnum + */ + @Override + public String getChannel() { + return ChannelEnum.UNION_PAY.getCode(); + } + + /** + * 退款前对处理, 初始化微信支付配置 + */ + @Override + public void doBeforeRefundHandler() { + this.unionPayConfig = unionPayConfigService.getAndCheckConfig(); + } + + + /** + * 退款操作 + */ + @Override + public RefundResultBo doRefundHandler() { + UnionPayKit unionPayKit = unionPayConfigService.initPayService(unionPayConfig); + return unionPayRefundService.refund(this.getRefundOrder(), unionPayKit); + } +} diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionSyncPayStrategy.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionSyncPayStrategy.java new file mode 100644 index 000000000..0ea00ffdb --- /dev/null +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionSyncPayStrategy.java @@ -0,0 +1,31 @@ +package org.dromara.daxpay.channel.union.strategy; + +import lombok.RequiredArgsConstructor; +import org.dromara.daxpay.core.enums.ChannelEnum; +import org.dromara.daxpay.service.bo.sync.PaySyncResultBo; +import org.dromara.daxpay.service.strategy.AbsSyncPayOrderStrategy; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE; + +/** + * 云闪付支付同步接口 + * @author xxm + * @since 2024/3/7 + */ +@Scope(SCOPE_PROTOTYPE) +@Component +@RequiredArgsConstructor +public class UnionSyncPayStrategy extends AbsSyncPayOrderStrategy { + + @Override + public PaySyncResultBo doSync() { + return null; + } + + @Override + public String getChannel() { + return ChannelEnum.UNION_PAY.getCode(); + } +} diff --git a/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionSyncRefundStrategy.java b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionSyncRefundStrategy.java new file mode 100644 index 000000000..87a277517 --- /dev/null +++ b/daxpay-single-channel/daxpay-single-union/src/main/java/org/dromara/daxpay/channel/union/strategy/UnionSyncRefundStrategy.java @@ -0,0 +1,30 @@ +package org.dromara.daxpay.channel.union.strategy; + +import lombok.RequiredArgsConstructor; +import org.dromara.daxpay.core.enums.ChannelEnum; +import org.dromara.daxpay.service.bo.sync.RefundSyncResultBo; +import org.dromara.daxpay.service.strategy.AbsSyncRefundOrderStrategy; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE; + +/** + * 云闪付退款同步 + * @author xxm + * @since 2024/3/11 + */ +@Scope(SCOPE_PROTOTYPE) +@Component +@RequiredArgsConstructor +public class UnionSyncRefundStrategy extends AbsSyncRefundOrderStrategy { + @Override + public RefundSyncResultBo doSync() { + return null; + } + + @Override + public String getChannel() { + return ChannelEnum.UNION_PAY.getCode(); + } +} diff --git a/daxpay-single/daxpay-single-core/src/main/java/org/dromara/daxpay/core/util/PayUtil.java b/daxpay-single/daxpay-single-core/src/main/java/org/dromara/daxpay/core/util/PayUtil.java index a8a4b8c05..22ca92e83 100644 --- a/daxpay-single/daxpay-single-core/src/main/java/org/dromara/daxpay/core/util/PayUtil.java +++ b/daxpay-single/daxpay-single-core/src/main/java/org/dromara/daxpay/core/util/PayUtil.java @@ -1,6 +1,5 @@ package org.dromara.daxpay.core.util; -import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.LocalDateTimeUtil; import jakarta.servlet.http.HttpServletRequest; import lombok.experimental.UtilityClass; @@ -21,14 +20,6 @@ import java.util.Map; public class PayUtil { private static final BigDecimal HUNDRED = new BigDecimal(100); - /** - * 获取云闪付的过期时间 yyyyMMddHHmmss - */ - @Deprecated - public String getUnionExpiredTime(LocalDateTime dateTime) { - return LocalDateTimeUtil.format(dateTime, DatePattern.PURE_DATETIME_PATTERN); - } - /** * 获取支付单的超时时间 */ diff --git a/daxpay-single/daxpay-single-unisdk/pom.xml b/daxpay-single/daxpay-single-unisdk/pom.xml index 702570099..1669eff3b 100644 --- a/daxpay-single/daxpay-single-unisdk/pom.xml +++ b/daxpay-single/daxpay-single-unisdk/pom.xml @@ -15,6 +15,35 @@ 21 21 UTF-8 + + 4.5.4 + 1.2.83_noneautotype + + + cn.bootx.platform + bootx-platform-core + ${bootx-platform.version} + + + + org.apache.httpcomponents + httpmime + ${httpmime.version} + + + + com.alibaba + fastjson + ${fastjson.version} + + + + + org.slf4j + slf4j-api + + + diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/BasePayConfigStorage.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/BasePayConfigStorage.java index a972d1518..2039542b2 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/BasePayConfigStorage.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/BasePayConfigStorage.java @@ -1,5 +1,8 @@ package org.dromara.daxpay.unisdk.common.api; +import lombok.Getter; +import lombok.Setter; + import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.Lock; @@ -15,52 +18,81 @@ import java.util.concurrent.locks.Lock; */ public abstract class BasePayConfigStorage implements PayConfigStorage { + @Setter private Object attach; /** * 应用私钥,rsa_private pkcs8格式 生成签名时使用 */ + @Setter private String keyPrivate; /** * 支付平台公钥(签名校验使用) */ + @Setter private String keyPublic; /** * 异步回调地址 */ + @Setter private String notifyUrl; /** * 同步回调地址,支付完成后展示的页面 */ + @Setter private String returnUrl; /** * 签名加密类型 */ + @Setter private String signType; /** * 字符类型 */ + @Setter private String inputCharset; /** * 支付类型 aliPay 支付宝, wxPay微信..等等,扩展支付模块定义唯一。 */ + @Setter private String payType; /** * 访问令牌 每次请求其他方法都要传入的值 + * -- GETTER -- + * 获取访问令牌 + * + * @return 访问令牌 + */ + @Setter + @Getter private volatile String accessToken; /** * access token 到期时间时间戳 + * -- GETTER -- + * 强制将access token过期掉 + * + * @return 过期时间 + */ + @Setter + @Getter private volatile long expiresTime; /** * 授权码锁 + * -- GETTER -- + * 获取access token锁 + * + * @return access token锁 + */ + @Setter + @Getter private Lock accessTokenLock; /** * 是否为沙箱环境,默认为正式环境 @@ -70,6 +102,8 @@ public abstract class BasePayConfigStorage implements PayConfigStorage { /** * 是否为证书签名 */ + @Setter + @Getter private boolean certSign = false; /** @@ -82,101 +116,42 @@ public abstract class BasePayConfigStorage implements PayConfigStorage { return attach; } - public void setAttach(Object attach) { - this.attach = attach; - } - @Override public String getKeyPrivate() { return keyPrivate; } - public void setKeyPrivate(String keyPrivate) { - this.keyPrivate = keyPrivate; - } - @Override public String getKeyPublic() { return keyPublic; } - public void setKeyPublic(String keyPublic) { - this.keyPublic = keyPublic; - } - @Override public String getNotifyUrl() { return notifyUrl; } - public void setNotifyUrl(String notifyUrl) { - this.notifyUrl = notifyUrl; - } - @Override public String getReturnUrl() { return returnUrl; } - public void setReturnUrl(String returnUrl) { - this.returnUrl = returnUrl; - } - @Override public String getSignType() { return signType; } - public void setSignType(String signType) { - this.signType = signType; - } - @Override public String getInputCharset() { return inputCharset; } - public void setInputCharset(String inputCharset) { - this.inputCharset = inputCharset; - } - @Override public String getPayType() { return payType; } - public void setPayType(String payType) { - this.payType = payType; - } - - /** - * 获取访问令牌 - * - * @return 访问令牌 - */ - public String getAccessToken() { - return this.accessToken; - } - - /** - * 获取access token锁 - * - * @return access token锁 - */ - public Lock getAccessTokenLock() { - return this.accessTokenLock; - } - - /** - * 强制将access token过期掉 - * - * @return 过期时间 - */ - public long getExpiresTime() { - return expiresTime; - } - /** * 访问令牌是否过期 * @@ -211,18 +186,6 @@ public abstract class BasePayConfigStorage implements PayConfigStorage { return null; } - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - public void setExpiresTime(long expiresTime) { - this.expiresTime = expiresTime; - } - - public void setAccessTokenLock(Lock accessTokenLock) { - this.accessTokenLock = accessTokenLock; - } - @Override public boolean isTest() { return isTest; @@ -232,14 +195,6 @@ public abstract class BasePayConfigStorage implements PayConfigStorage { isTest = test; } - public boolean isCertSign() { - return certSign; - } - - public void setCertSign(boolean certSign) { - this.certSign = certSign; - } - @Override public Map getAttrs() { if (null == attr) { diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/BasePayService.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/BasePayService.java index 8fe60b7f8..6dbd02b0b 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/BasePayService.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/BasePayService.java @@ -1,15 +1,14 @@ package org.dromara.daxpay.unisdk.common.api; import com.alibaba.fastjson.JSON; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.Consts; import org.dromara.daxpay.unisdk.common.bean.*; import org.dromara.daxpay.unisdk.common.http.HttpConfigStorage; import org.dromara.daxpay.unisdk.common.http.HttpRequestTemplate; -import org.dromara.daxpay.unisdk.common.util.MatrixToImageWriter; import org.dromara.daxpay.unisdk.common.util.sign.SignUtils; import org.dromara.daxpay.unisdk.common.util.str.StringUtils; -import org.apache.http.Consts; -import java.awt.image.BufferedImage; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; @@ -24,8 +23,8 @@ import java.util.*; * date 2017/3/5 20:36 * */ +@Slf4j public abstract class BasePayService implements PayService { - protected final Logger LOG = LoggerFactory.getLogger(getClass()); protected PC payConfigStorage; protected HttpRequestTemplate requestTemplate; @@ -39,7 +38,7 @@ public abstract class BasePayService implements Pay /** * 支付消息拦截器 */ - protected List> interceptors = new ArrayList>(); + protected List> interceptors = new ArrayList<>(); private Charset inputCharset = Consts.UTF_8; @@ -105,7 +104,7 @@ public abstract class BasePayService implements Pay base64ClientID = org.dromara.daxpay.unisdk.common.util.sign.encrypt.Base64.encode(String.format("%s:%s", user, password).getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { - LOG.error("", e); + log.error("", e); } return base64ClientID; @@ -166,16 +165,6 @@ public abstract class BasePayService implements Pay return orderInfo(order); } - /** - * 生成二维码支付 - * - * @param order 发起支付的订单信息 - * @return 返回图片信息,支付时需要的 - */ - @Override - public BufferedImage genQrPay(O order) { - return MatrixToImageWriter.writeInfoToJpgBuff(getQrPay(order)); - } /** * 小程序支付,返回小程序所需的订单构建信息 @@ -188,18 +177,6 @@ public abstract class BasePayService implements Pay return Collections.emptyMap(); } - /** - * 将请求参数或者请求流转化为 Map - * - * @param parameterMap 请求参数 - * @param is 请求流 - * @return 获得回调的请求参数 - */ - @Override - public Map getParameter2Map(Map parameterMap, InputStream is) { - return getNoticeParams(new DefaultNoticeRequest(parameterMap, is)).getBody(); - } - /** * 将请求参数或者请求流转化为 Map * @@ -229,50 +206,6 @@ public abstract class BasePayService implements Pay return new NoticeParams(params); } - /** - * 交易查询接口,带处理器 - * - * @param tradeNo 支付平台订单号 - * @param outTradeNo 商户单号 - * @param callback 处理器 - * @param 返回类型 - * @return 返回查询回来的结果集 - */ - @Override - public T query(String tradeNo, String outTradeNo, Callback callback) { - - return callback.perform(query(tradeNo, outTradeNo)); - } - - /** - * 交易关闭接口 - * - * @param tradeNo 支付平台订单号 - * @param outTradeNo 商户单号 - * @param callback 处理器 - * @param 返回类型 - * @return 返回支付方交易关闭后的结果 - */ - @Deprecated - @Override - public T close(String tradeNo, String outTradeNo, Callback callback) { - return callback.perform(close(tradeNo, outTradeNo)); - } - - /** - * 交易撤销 - * - * @param tradeNo 支付平台订单号 - * @param outTradeNo 商户单号 - * @param callback 处理器 - * @param 返回类型 - * @return 返回支付方交易撤销后的结果 - */ - @Override - public T cancel(String tradeNo, String outTradeNo, Callback callback) { - return callback.perform(cancel(tradeNo, outTradeNo)); - } - /** * 交易交易撤销 * @@ -286,34 +219,6 @@ public abstract class BasePayService implements Pay } - /** - * 申请退款接口 - * - * @param refundOrder 退款订单信息 - * @param callback 处理器 - * @param 返回类型 - * @return 返回支付方申请退款后的结果 - */ - @Override - public T refund(RefundOrder refundOrder, Callback callback) { - - return callback.perform(refund(refundOrder).getAttrs()); - } - - - /** - * 查询退款 - * - * @param refundOrder 退款订单信息 - * @param callback 处理器 - * @param 返回类型 - * @return 返回支付方查询退款后的结果 - */ - @Override - public T refundquery(RefundOrder refundOrder, Callback callback) { - return callback.perform(refundquery(refundOrder)); - } - /** * 下载对账单 * @@ -326,19 +231,6 @@ public abstract class BasePayService implements Pay return Collections.emptyMap(); } - /** - * 转账 - * - * @param order 转账订单 - * @param callback 处理器 - * @return 对应的转账结果 - */ - @Override - public T transfer(TransferOrder order, Callback callback) { - return callback.perform(transfer(order)); - } - - /** * 转账 * @@ -350,32 +242,6 @@ public abstract class BasePayService implements Pay return Collections.emptyMap(); } - /** - * 转账查询 - * - * @param outNo 商户转账订单号 - * @param tradeNo 支付平台转账订单号 - * @return 对应的转账订单 - */ - @Override - public Map transferQuery(String outNo, String tradeNo) { - return Collections.emptyMap(); - } - - /** - * 转账查询 - * - * @param outNo 商户转账订单号 - * @param tradeNo 支付平台转账订单号 - * @param callback 处理器 - * @param 返回类型 - * @return 对应的转账订单 - */ - @Override - public T transferQuery(String outNo, String tradeNo, Callback callback) { - return callback.perform(transferQuery(outNo, tradeNo)); - } - /** * 设置支付消息处理器,这里用于处理具体的支付业务 * @@ -415,19 +281,6 @@ public abstract class BasePayService implements Pay } - /** - * 将请求参数或者请求流转化为 Map - * - * @param parameterMap 请求参数 - * @param is 请求流 - * @return 获得回调响应信息 - */ - @Deprecated - @Override - public PayOutMessage payBack(Map parameterMap, InputStream is) { - return payBack(new DefaultNoticeRequest(parameterMap, is)); - } - /** * 回调处理 * @@ -437,8 +290,8 @@ public abstract class BasePayService implements Pay @Override public PayOutMessage payBack(NoticeRequest request) { final NoticeParams noticeParams = getNoticeParams(request); - if (LOG.isDebugEnabled()) { - LOG.debug("回调响应:{}", JSON.toJSONString(noticeParams)); + if (log.isDebugEnabled()) { + log.debug("回调响应:{}", JSON.toJSONString(noticeParams)); } if (!verify(noticeParams)) { return getPayOutMessage("fail", "失败"); @@ -464,45 +317,4 @@ public abstract class BasePayService implements Pay return new PayMessage(message); } - /** - * 预订单回调处理器,用于订单信息的扩展 - * 签名之前使用 - * 如果需要进行扩展请重写该方法即可 - * - * @param orderInfo 预订单信息 - * @param orderInfo 订单信息 - * @return 处理后订单信息 - */ - @Override - public Map preOrderHandler(Map orderInfo, O payOrder) { - return orderInfo; - } - - /** - * 过时 - * - * @param parameters 参数map - * @param key key - * @param value 值 - * @return 返回订单参数 - */ - @Deprecated - protected Map setParameters(Map parameters, String key, String value) { - return OrderParaStructure.loadParameters(parameters, key, value); - } - - /** - * 过时 - * - * @param parameters 参数map - * @param key key - * @param order 订单对象 - * @return 返回订单参数 - */ - @Deprecated - protected Map setParameters(Map parameters, String key, Order order) { - return OrderParaStructure.loadParameters(parameters, key, order); - } - - } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/DefaultPayMessageHandler.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/DefaultPayMessageHandler.java index 1f4d3e12f..2f80f41bc 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/DefaultPayMessageHandler.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/DefaultPayMessageHandler.java @@ -1,6 +1,7 @@ package org.dromara.daxpay.unisdk.common.api; import com.alibaba.fastjson.JSON; +import lombok.extern.slf4j.Slf4j; import org.dromara.daxpay.unisdk.common.bean.PayMessage; import org.dromara.daxpay.unisdk.common.bean.PayOutMessage; import org.dromara.daxpay.unisdk.common.exception.PayErrorException; @@ -19,6 +20,7 @@ import java.util.Map; * date 2018-10-29 17:31:05 * */ +@Slf4j public class DefaultPayMessageHandler implements PayMessageHandler { protected final Logger LOG = LoggerFactory.getLogger(DefaultPayMessageHandler.class); @@ -30,8 +32,8 @@ public class DefaultPayMessageHandler implements PayMessageHandler context, PayService payService) throws PayErrorException { - if (LOG.isInfoEnabled()) { - LOG.info("回调支付消息处理器,回调消息:" + JSON.toJSONString(payMessage)); + if (log.isInfoEnabled()) { + log.info("回调支付消息处理器,回调消息:" + JSON.toJSONString(payMessage)); } return payService.successPayOutMessage(payMessage); } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayConfigStorage.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayConfigStorage.java index 32a677474..d28a8573e 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayConfigStorage.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayConfigStorage.java @@ -20,16 +20,6 @@ public interface PayConfigStorage extends Attrs { */ Object getAttach(); - /** - * 应用id - * 纠正名称 - * - * @return 应用id - * @see #getAppId() - */ - @Deprecated - String getAppid(); - /** * 应用id * 纠正名称 diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayMessageRouter.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayMessageRouter.java index dbf418699..5886dd87a 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayMessageRouter.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayMessageRouter.java @@ -1,10 +1,10 @@ package org.dromara.daxpay.unisdk.common.api; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; import org.dromara.daxpay.unisdk.common.bean.PayMessage; import org.dromara.daxpay.unisdk.common.bean.PayOutMessage; import org.dromara.daxpay.unisdk.common.util.LogExceptionHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; @@ -42,8 +42,8 @@ import java.util.concurrent.Future; * * @author egan */ +@Slf4j public class PayMessageRouter { - protected final Logger LOG = LoggerFactory.getLogger(PayMessageRouter.class); /** * 异步线程大小 @@ -59,11 +59,29 @@ public class PayMessageRouter { private final PayService payService; /** * 异步线程处理器 + * -- SETTER -- + *
+     *  设置自定义的
+     *  如果不调用用该方法,默认使 Executors.newFixedThreadPool(100)
+     *  
+ * + * @param executorService 异步线程处理器 + */ + @Setter private ExecutorService executorService; /** * 支付异常处理器 + * -- SETTER -- + *
+     *  设置自定义的
+     *  如果不调用该方法,默认使用
+     *  
+ * + * @param exceptionHandler 异常处理器 + */ + @Setter private PayErrorExceptionHandler exceptionHandler; /** @@ -77,30 +95,6 @@ public class PayMessageRouter { this.exceptionHandler = new LogExceptionHandler(); } - /** - *
-     * 设置自定义的 {@link ExecutorService}
-     * 如果不调用用该方法,默认使 Executors.newFixedThreadPool(100)
-     * 
- * - * @param executorService 异步线程处理器 - */ - public void setExecutorService(ExecutorService executorService) { - this.executorService = executorService; - } - - - /** - *
-     * 设置自定义的{@link PayErrorExceptionHandler}
-     * 如果不调用该方法,默认使用 {@link LogExceptionHandler}
-     * 
- * - * @param exceptionHandler 异常处理器 - */ - public void setExceptionHandler(PayErrorExceptionHandler exceptionHandler) { - this.exceptionHandler = exceptionHandler; - } /** * 获取所有的规则 @@ -163,39 +157,33 @@ public class PayMessageRouter { // 返回最后一个非异步的rule的执行结果 if (rule.isAsync()) { futures.add( - executorService.submit(new Runnable() { - @Override - public void run() { - rule.service(payMessage, payService, exceptionHandler); - } + executorService.submit(() -> { + rule.service(payMessage, payService, exceptionHandler); }) ); } else { res = rule.service(payMessage, payService, exceptionHandler); // 在同步操作结束,session访问结束 - if (LOG.isDebugEnabled()) { - LOG.debug("End session access: async=false, fromPay=" + payMessage.getFromPay()); + if (log.isDebugEnabled()) { + log.debug("End session access: async=false, fromPay=" + payMessage.getFromPay()); } } } - if (futures.size() > 0) { - executorService.submit(new Runnable() { - @Override - public void run() { - for (Future future : futures) { - try { - future.get(); - LOG.debug("End session access: async=true, fromPay=" + payMessage.getFromPay()); + if (!futures.isEmpty()) { + executorService.submit(() -> { + for (Future future : futures) { + try { + future.get(); + log.debug("End session access: async=true, fromPay=" + payMessage.getFromPay()); - } - catch (InterruptedException e) { - LOG.error("Error happened when wait task finish", e); - } - catch (ExecutionException e) { - LOG.error("Error happened when wait task finish", e); - } + } + catch (InterruptedException e) { + log.error("Error happened when wait task finish", e); + } + catch (ExecutionException e) { + log.error("Error happened when wait task finish", e); } } }); diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayMessageRouterRule.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayMessageRouterRule.java index b77996578..1fd901529 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayMessageRouterRule.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayMessageRouterRule.java @@ -1,14 +1,13 @@ package org.dromara.daxpay.unisdk.common.api; +import lombok.Getter; +import lombok.Setter; import org.dromara.daxpay.unisdk.common.bean.PayMessage; import org.dromara.daxpay.unisdk.common.bean.PayOutMessage; import org.dromara.daxpay.unisdk.common.exception.PayErrorException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.regex.Pattern; @@ -24,6 +23,7 @@ import java.util.regex.Pattern; * source chanjarster/weixin-java-tools * */ +@Getter public class PayMessageRouterRule { @@ -31,37 +31,47 @@ public class PayMessageRouterRule { /** * 默认同步 */ + @Setter private boolean async = false; /** * 支付类型 */ + @Setter private String payType; /** * 交易类型 */ + @Setter private String[] transactionType; /** * 简介 */ + @Setter private String subject; /** * 正则匹配 */ + @Setter private String rSubject; /** * 匹配的键名称 */ + @Setter private String key; /** * 匹配的键名称对应的值 正则 */ + @Setter private String rValue; + @Setter private boolean reEnter = false; + @Setter private List handlers = new ArrayList(); + @Setter private List interceptors = new ArrayList(); public PayMessageRouterRule(PayMessageRouter routerBuilder) { @@ -159,9 +169,7 @@ public class PayMessageRouterRule { public PayMessageRouterRule interceptor(PayMessageInterceptor interceptor, PayMessageInterceptor... otherInterceptors) { this.interceptors.add(interceptor); if (otherInterceptors != null && otherInterceptors.length > 0) { - for (PayMessageInterceptor i : otherInterceptors) { - this.interceptors.add(i); - } + this.interceptors.addAll(Arrays.asList(otherInterceptors)); } return this; } @@ -186,9 +194,7 @@ public class PayMessageRouterRule { public PayMessageRouterRule handler(PayMessageHandler handler, PayMessageHandler... otherHandlers) { this.handlers.add(handler); if (otherHandlers != null && otherHandlers.length > 0) { - for (PayMessageHandler i : otherHandlers) { - this.handlers.add(i); - } + this.handlers.addAll(Arrays.asList(otherHandlers)); } return this; } @@ -250,7 +256,7 @@ public class PayMessageRouterRule { } for (String type : this.getTransactionType()) { - if (type.toLowerCase().equals((transactionType.toLowerCase()))) { + if (type.equalsIgnoreCase((transactionType))) { return true; } } @@ -297,87 +303,4 @@ public class PayMessageRouterRule { } - public PayMessageRouter getRouterBuilder() { - return routerBuilder; - } - - public boolean isAsync() { - return async; - } - - public void setAsync(boolean async) { - this.async = async; - } - - public String getPayType() { - return payType; - } - - public void setPayType(String payType) { - this.payType = payType; - } - - public String[] getTransactionType() { - return transactionType; - } - - public void setTransactionType(String[] transactionType) { - this.transactionType = transactionType; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getrValue() { - return rValue; - } - - public void setrValue(String rValue) { - this.rValue = rValue; - } - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public String getrSubject() { - return rSubject; - } - - public void setrSubject(String rSubject) { - this.rSubject = rSubject; - } - - public boolean isReEnter() { - return reEnter; - } - - public void setReEnter(boolean reEnter) { - this.reEnter = reEnter; - } - - public List getHandlers() { - return handlers; - } - - public void setHandlers(List handlers) { - this.handlers = handlers; - } - - public List getInterceptors() { - return interceptors; - } - - public void setInterceptors(List interceptors) { - this.interceptors = interceptors; - } } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayService.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayService.java index 2c69f91b4..bf1c4e215 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayService.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/api/PayService.java @@ -4,8 +4,6 @@ import org.dromara.daxpay.unisdk.common.bean.*; import org.dromara.daxpay.unisdk.common.http.HttpConfigStorage; import org.dromara.daxpay.unisdk.common.http.HttpRequestTemplate; -import java.awt.image.BufferedImage; -import java.io.InputStream; import java.util.Date; import java.util.Map; @@ -51,16 +49,6 @@ public interface PayService { */ PayService setRequestTemplateConfigStorage(HttpConfigStorage configStorage); - /** - * 回调校验 - * 已过时方法,详情{@link #verify(NoticeParams)} - * @param params 回调回来的参数集 - * @return 签名校验 true通过 - * @see #verify(NoticeParams) - */ - @Deprecated - boolean verify(Map params); - /** * 回调校验 * @@ -107,18 +95,6 @@ public interface PayService { */ String createSign(String content, String characterEncoding); - - /** - * 将请求参数或者请求流转化为 Map - * - * @param parameterMap 请求参数 - * @param is 请求流 - * @return 获得回调的请求参数 - * @see #getNoticeParams(NoticeRequest) - */ - @Deprecated - Map getParameter2Map(Map parameterMap, InputStream is); - /** * 将请求参数或者请求流转化为 Map * @@ -156,15 +132,6 @@ public interface PayService { String buildRequest(Map orderInfo, MethodType method); - /** - * 获取输出二维码,用户返回给支付端, - * - * @param order 发起支付的订单信息 - * @param 预订单类型 - * @return 返回图片信息,支付时需要的 - */ - BufferedImage genQrPay(O order); - /** * 获取输出二维码信息, * @@ -192,29 +159,6 @@ public interface PayService { */ Map microPay(O order); - /** - * 交易查询接口 - * - * @param tradeNo 支付平台订单号 - * @param outTradeNo 商户单号 - * @return 返回查询回来的结果集,支付方原值返回 - * @see #query(AssistOrder) - */ - @Deprecated - Map query(String tradeNo, String outTradeNo); - - /** - * 交易查询接口,带处理器 - * - * @param tradeNo 支付平台订单号 - * @param outTradeNo 商户单号 - * @param callback 处理器 - * @param 返回类型 - * @return 返回查询回来的结果集 - */ - @Deprecated - T query(String tradeNo, String outTradeNo, Callback callback); - /** * 交易查询接口 @@ -225,16 +169,6 @@ public interface PayService { Map query(AssistOrder assistOrder); - /** - * 交易关闭接口 - * - * @param tradeNo 支付平台订单号 - * @param outTradeNo 商户单号 - * @return 返回支付方交易关闭后的结果 - * @see #close(AssistOrder) - */ - @Deprecated - Map close(String tradeNo, String outTradeNo); /** * 交易关闭接口 @@ -245,19 +179,6 @@ public interface PayService { Map close(AssistOrder assistOrder); - /** - * 交易关闭接口 - * - * @param tradeNo 支付平台订单号 - * @param outTradeNo 商户单号 - * @param callback 处理器 - * @param 返回类型 - * @return 返回支付方交易关闭后的结果 - */ - @Deprecated - T close(String tradeNo, String outTradeNo, Callback callback); - - /** * 交易交易撤销 * @@ -267,18 +188,6 @@ public interface PayService { */ Map cancel(String tradeNo, String outTradeNo); - /** - * 交易交易撤销 - * - * @param tradeNo 支付平台订单号 - * @param outTradeNo 商户单号 - * @param callback 处理器 - * @param 返回类型 - * @return 返回支付方交易撤销后的结果 - */ - @Deprecated - T cancel(String tradeNo, String outTradeNo, Callback callback); - /** * 申请退款接口 @@ -288,17 +197,6 @@ public interface PayService { */ RefundResult refund(RefundOrder refundOrder); - /** - * 申请退款接口 - * - * @param refundOrder 退款订单信息 - * @param callback 处理器 - * @param 返回类型 - * @return 返回支付方申请退款后的结果 - */ - @Deprecated - T refund(RefundOrder refundOrder, Callback callback); - /** * 查询退款 @@ -308,17 +206,6 @@ public interface PayService { */ Map refundquery(RefundOrder refundOrder); - /** - * 查询退款 - * - * @param refundOrder 退款订单信息 - * @param callback 处理器 - * @param 返回类型 - * @return 返回支付方查询退款后的结果 - */ - @Deprecated - T refundquery(RefundOrder refundOrder, Callback callback); - /** * 下载对账单 * @@ -346,52 +233,6 @@ public interface PayService { */ Map transfer(TransferOrder order); - /** - * 转账 - * - * @param order 转账订单 - * @param callback 处理器 - * @param 返回类型 - * @return 对应的转账结果 - */ - @Deprecated - T transfer(TransferOrder order, Callback callback); - - - /** - * 转账查询 - * - * @param outNo 商户转账订单号 - * @param tradeNo 支付平台转账订单号 - * @return 对应的转账订单 - * @deprecated 替代{@link TransferService#transferQuery(org.dromara.daxpay.unisdk.common.bean.AssistOrder)} - */ - @Deprecated - Map transferQuery(String outNo, String tradeNo); - - /** - * 转账查询 - * - * @param outNo 商户转账订单号 - * @param tradeNo 支付平台转账订单号 - * @param callback 处理器 - * @param 返回类型 - * @return 对应的转账订单 - */ - @Deprecated - T transferQuery(String outNo, String tradeNo, Callback callback); - - /** - * 回调处理 - * - * @param parameterMap 请求参数 - * @param is 请求流 - * @return 获得回调响应信息 - * 过时方法,详情查看 {@link #payBack(NoticeRequest)} - */ - @Deprecated - PayOutMessage payBack(Map parameterMap, InputStream is); - /** * 回调处理 * @@ -437,17 +278,4 @@ public interface PayService { */ PayMessage createMessage(Map message); - /** - * 预订单回调处理器,用于订单信息的扩展 - * 签名之前使用 - * 如果需要进行扩展请重写该方法即可 - * - * @param orderInfo 商户平台预订单信息 - * @param payOrder 订单信息 - * @param 预订单类型 - * @return 处理后订单信息 - */ - @Deprecated - Map preOrderHandler(Map orderInfo, O payOrder); - } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/AssistOrder.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/AssistOrder.java index 8ebf9f6bf..3346cb9b8 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/AssistOrder.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/AssistOrder.java @@ -1,6 +1,8 @@ package org.dromara.daxpay.unisdk.common.bean; import com.alibaba.fastjson.annotation.JSONField; +import lombok.Getter; +import lombok.Setter; import java.util.HashMap; import java.util.Map; @@ -19,20 +21,48 @@ public class AssistOrder implements Order { /** * 支付平台订单号,交易号, 平台批次单号 + * -- GETTER -- + * 支付平台订单号,交易号 + * + * + * -- SETTER -- + * 支付平台订单号,交易号 + * + @return 支付平台订单号, 交易号 + * @param tradeNo 支付平台订单号,交易号 + */ + @Setter + @Getter private String tradeNo; /** * 商户订单号,商家批次单号 + * -- GETTER -- + * 获取商户订单号,商家批次单号 + * + * + * -- SETTER -- + * 设置商户订单号,商家批次单号 + * + @return 商户订单号, 商家批次单号 + * @param outTradeNo 商户订单号,商家批次单号 + */ + @Setter + @Getter private String outTradeNo; /** * 交易类型 */ + @Setter + @Getter private TransactionType transactionType; /** * 异步回调通知 */ + @Setter + @Getter private String notifyUrl; /** @@ -58,50 +88,6 @@ public class AssistOrder implements Order { this.transactionType = transactionType; } - /** - * 支付平台订单号,交易号 - * - * @return 支付平台订单号, 交易号 - */ - public String getTradeNo() { - return tradeNo; - } - - /** - * 支付平台订单号,交易号 - * - * @param tradeNo 支付平台订单号,交易号 - */ - public void setTradeNo(String tradeNo) { - this.tradeNo = tradeNo; - } - - /** - * 获取商户订单号,商家批次单号 - * - * @return 商户订单号, 商家批次单号 - */ - public String getOutTradeNo() { - return outTradeNo; - } - - /** - * 设置商户订单号,商家批次单号 - * - * @param outTradeNo 商户订单号,商家批次单号 - */ - public void setOutTradeNo(String outTradeNo) { - this.outTradeNo = outTradeNo; - } - - public TransactionType getTransactionType() { - return transactionType; - } - - public void setTransactionType(TransactionType transactionType) { - this.transactionType = transactionType; - } - @Override public Map getAttrs() { @@ -128,11 +114,4 @@ public class AssistOrder implements Order { getAttrs().put(key, value); } - public String getNotifyUrl() { - return notifyUrl; - } - - public void setNotifyUrl(String notifyUrl) { - this.notifyUrl = notifyUrl; - } } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/BaseRefundResult.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/BaseRefundResult.java index 4259b14e9..3790e837c 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/BaseRefundResult.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/BaseRefundResult.java @@ -1,5 +1,7 @@ package org.dromara.daxpay.unisdk.common.bean; +import lombok.Setter; + import java.math.BigDecimal; import java.util.Map; @@ -12,6 +14,7 @@ import java.util.Map; * date 2020/8/16 19:29 * */ +@Setter public abstract class BaseRefundResult implements RefundResult { /** @@ -38,10 +41,6 @@ public abstract class BaseRefundResult implements RefundResult { return attrs; } - public void setAttrs(Map attrs) { - this.attrs = attrs; - } - /** * 获取退款结果属性值 * diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/CertStoreType.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/CertStoreType.java index 3db9982b4..ad51cec20 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/CertStoreType.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/CertStoreType.java @@ -45,7 +45,7 @@ public enum CertStoreType implements CertStore { */ @Override public InputStream getInputStream(Object cert) throws IOException { - return new FileInputStream(new File((String) cert)); + return new FileInputStream((String) cert); } }, /** @@ -130,7 +130,7 @@ public enum CertStoreType implements CertStore { public InputStream getInputStream(Object beanClazz) throws IOException { try { Class clazz = Class.forName((String) beanClazz); - CertStore certStore = (CertStore)clazz.newInstance(); + CertStore certStore = (CertStore)clazz.getDeclaredConstructor().newInstance(); return certStore.getInputStream(beanClazz); } catch (ReflectiveOperationException e) { throw new PayErrorException(new PayException("证书获取异常", e.getMessage())); diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/CloseOrder.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/CloseOrder.java deleted file mode 100644 index 503b8a088..000000000 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/CloseOrder.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.dromara.daxpay.unisdk.common.bean; - -/** - * 关闭订单 - * @author Egan - *
- * email egan@egzosn.com
- * date 2021/10/6
- * 
- */ -@Deprecated -public class CloseOrder extends AssistOrder { - -} diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/DefaultCountryCode.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/DefaultCountryCode.java index 78e185896..a27177d4e 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/DefaultCountryCode.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/DefaultCountryCode.java @@ -19,7 +19,7 @@ public enum DefaultCountryCode implements CountryCode{ /** * 国家名称 */ - private String name; + private final String name; DefaultCountryCode(String name) { this.name = name; diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/DefaultCurType.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/DefaultCurType.java index a7e43088e..1cf95a102 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/DefaultCurType.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/DefaultCurType.java @@ -23,7 +23,7 @@ public enum DefaultCurType implements CurType{ /** * 币种名称 */ - private String name; + private final String name; /** * 构造函数 diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/DefaultNoticeRequest.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/DefaultNoticeRequest.java index 955bb6217..68c2ad474 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/DefaultNoticeRequest.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/DefaultNoticeRequest.java @@ -48,7 +48,7 @@ public class DefaultNoticeRequest implements NoticeRequest { @Override public String getHeader(String name) { List value = this.headers.get(name); - return (null == value || value.isEmpty()) ? null : value.get(0); + return (null == value || value.isEmpty()) ? null : value.getFirst(); } /** diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/NoticeParams.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/NoticeParams.java index a66dbf5f4..ee21a99f8 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/NoticeParams.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/NoticeParams.java @@ -17,6 +17,9 @@ package org.dromara.daxpay.unisdk.common.bean; +import lombok.Getter; +import lombok.Setter; + import java.util.Collections; import java.util.Enumeration; import java.util.List; @@ -29,6 +32,8 @@ import java.util.Map; * email egzosn@gmail.com * date 2021/8/8 */ +@Setter +@Getter public class NoticeParams implements Attrs { /** @@ -63,14 +68,6 @@ public class NoticeParams implements Attrs { this.headers = headers; } - public String getBodyStr() { - return bodyStr; - } - - public void setBodyStr(String bodyStr) { - this.bodyStr = bodyStr; - } - private T getValueMatchingKey(Map values, String key) { T value = values.get(key); if (null != value) { @@ -88,7 +85,7 @@ public class NoticeParams implements Attrs { public String getHeader(String name) { List value = getValueMatchingKey(headers, name); - return (null == value || value.isEmpty()) ? null : value.get(0); + return (null == value || value.isEmpty()) ? null : value.getFirst(); } public Enumeration getHeaders(String name) { @@ -104,31 +101,6 @@ public class NoticeParams implements Attrs { } - public Map getBody() { - return body; - } - - public void setBody(Map body) { - this.body = body; - } - - public Map> getHeaders() { - return headers; - } - - public void setHeaders(Map> headers) { - this.headers = headers; - } - - public Map getAttr() { - return attr; - } - - public void setAttr(Map attr) { - this.attr = attr; - } - - /** * 获取属性 这里可用做覆盖已设置的信息属性,订单信息在签名前进行覆盖。 * diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/PayMessage.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/PayMessage.java index 321b97ffa..08447b37b 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/PayMessage.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/PayMessage.java @@ -1,5 +1,8 @@ package org.dromara.daxpay.unisdk.common.bean; +import lombok.Getter; +import lombok.Setter; + import java.io.Serializable; import java.math.BigDecimal; import java.util.Map; @@ -14,11 +17,16 @@ import java.util.Map; * date 2017/3/7 16:37 * */ +@Getter public class PayMessage implements Serializable { private Map payMessage = null; + @Setter private String payType; + @Setter private String transactionType; + @Setter private String fromPay; + @Setter private String describe; @@ -46,38 +54,6 @@ public class PayMessage implements Serializable { } - public String getPayType() { - return payType; - } - - public void setPayType(String payType) { - this.payType = payType; - } - - public String getTransactionType() { - return transactionType; - } - - public void setTransactionType(String transactionType) { - this.transactionType = transactionType; - } - - public String getFromPay() { - return fromPay; - } - - public void setFromPay(String fromPay) { - this.fromPay = fromPay; - } - - public String getDescribe() { - return describe; - } - - public void setDescribe(String describe) { - this.describe = describe; - } - public String getDiscount() { return (String) payMessage.get("discount"); } @@ -98,7 +74,7 @@ public class PayMessage implements Serializable { public Number getTotalFee() { String totalFee = (String) payMessage.get("total_fee"); - if (null == totalFee || "".equals(totalFee)) { + if (null == totalFee || totalFee.isEmpty()) { return 0; } if (isNumber(totalFee)) { @@ -120,9 +96,5 @@ public class PayMessage implements Serializable { return payMessage.toString(); } - public Map getPayMessage() { - return payMessage; - } - } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/PayOrder.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/PayOrder.java index 5aa0c84fa..67aca5abf 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/PayOrder.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/PayOrder.java @@ -1,6 +1,7 @@ package org.dromara.daxpay.unisdk.common.bean; -import org.dromara.daxpay.unisdk.common.util.str.StringUtils; +import lombok.Getter; +import lombok.Setter; import java.math.BigDecimal; import java.util.Date; @@ -14,6 +15,8 @@ import java.util.Date; * date 2016/10/19 22:34 * */ +@Setter +@Getter public class PayOrder extends AssistOrder { /** * 商品名称 @@ -36,32 +39,10 @@ public class PayOrder extends AssistOrder { * 银行卡类型 */ private String bankType; - /** - * 设备信息 - */ - @Deprecated - private String deviceInfo; - /** - * 支付创建ip - */ - @Deprecated - private String spbillCreateIp; /** * 付款条码串,人脸凭证,有关支付代码相关的, */ private String authCode; - /** - * 微信专用,,,, - * WAP支付链接 - */ - @Deprecated - private String wapUrl; - /** - * 微信专用,,,, - * WAP支付网页名称 - */ - @Deprecated - private String wapName; /** * 用户唯一标识 * 微信含 sub_openid 字段 @@ -79,126 +60,4 @@ public class PayOrder extends AssistOrder { private Date expirationTime; - public PayOrder() { - } - - - public PayOrder(String subject, String body, BigDecimal price, String outTradeNo) { - this(subject, body, price, outTradeNo, null); - } - - public PayOrder(String subject, String body, BigDecimal price, String outTradeNo, TransactionType transactionType) { - this.subject = StringUtils.tryTrim(subject); - this.body = StringUtils.tryTrim(body); - this.price = price; - setOutTradeNo(StringUtils.tryTrim(outTradeNo)); - setTransactionType(transactionType); - } - - - public CurType getCurType() { - return curType; - } - - public void setCurType(CurType curType) { - this.curType = curType; - } - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - - public String getAddition() { - return addition; - } - - public void setAddition(String addition) { - this.addition = addition; - } - - public BigDecimal getPrice() { - return price; - } - - public void setPrice(BigDecimal price) { - this.price = price; - } - - - public String getBankType() { - return bankType; - } - - public void setBankType(String bankType) { - this.bankType = bankType; - } - - public String getSpbillCreateIp() { - return spbillCreateIp; - } - - public void setSpbillCreateIp(String spbillCreateIp) { - this.spbillCreateIp = spbillCreateIp; - } - - public String getAuthCode() { - return authCode; - } - - public void setAuthCode(String authCode) { - this.authCode = authCode; - } - - public String getDeviceInfo() { - return deviceInfo; - } - - public void setDeviceInfo(String deviceInfo) { - this.deviceInfo = deviceInfo; - } - - public String getWapUrl() { - return wapUrl; - } - - public void setWapUrl(String wapUrl) { - this.wapUrl = wapUrl; - } - - public String getWapName() { - return wapName; - } - - public void setWapName(String wapName) { - this.wapName = wapName; - } - - public String getOpenid() { - return openid; - } - - public void setOpenid(String openid) { - this.openid = openid; - } - - public Date getExpirationTime() { - return expirationTime; - } - - public void setExpirationTime(Date expirationTime) { - this.expirationTime = expirationTime; - } - } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/PayOutMessage.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/PayOutMessage.java index cd1d67ecc..8b9888944 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/PayOutMessage.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/PayOutMessage.java @@ -1,6 +1,8 @@ package org.dromara.daxpay.unisdk.common.bean; import com.alibaba.fastjson.JSONObject; +import lombok.Getter; +import lombok.Setter; import org.dromara.daxpay.unisdk.common.bean.outbuilder.JsonBuilder; import org.dromara.daxpay.unisdk.common.bean.outbuilder.TextBuilder; import org.dromara.daxpay.unisdk.common.bean.outbuilder.XmlBuilder; @@ -16,18 +18,12 @@ import java.io.Serializable; * date 2016-6-1 11:40:30 * */ +@Setter +@Getter public abstract class PayOutMessage implements Serializable { protected String content; - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - /** * 获得文本消息builder * diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/RefundOrder.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/RefundOrder.java index 158c09d5f..87906d287 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/RefundOrder.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/RefundOrder.java @@ -1,5 +1,8 @@ package org.dromara.daxpay.unisdk.common.bean; +import lombok.Getter; +import lombok.Setter; + import java.math.BigDecimal; import java.util.Date; @@ -12,6 +15,8 @@ import java.util.Date; * date 2018/1/15 21:40 * */ +@Setter +@Getter public class RefundOrder extends AssistOrder { /** * 退款单号,每次进行退款的单号,此处唯一 @@ -49,62 +54,6 @@ public class RefundOrder extends AssistOrder { */ private String refundUrl; - public String getRefundNo() { - return refundNo; - } - - public void setRefundNo(String refundNo) { - this.refundNo = refundNo; - } - - public BigDecimal getRefundAmount() { - return refundAmount; - } - - public void setRefundAmount(BigDecimal refundAmount) { - this.refundAmount = refundAmount; - } - - public BigDecimal getTotalAmount() { - return totalAmount; - } - - public void setTotalAmount(BigDecimal totalAmount) { - this.totalAmount = totalAmount; - } - - public Date getOrderDate() { - return orderDate; - } - - public void setOrderDate(Date orderDate) { - this.orderDate = orderDate; - } - - public CurType getCurType() { - return curType; - } - - public void setCurType(CurType curType) { - this.curType = curType; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - public RefundOrder() { } @@ -129,11 +78,4 @@ public class RefundOrder extends AssistOrder { this.totalAmount = totalAmount; } - public String getRefundUrl() { - return refundUrl; - } - - public void setRefundUrl(String refundUrl) { - this.refundUrl = refundUrl; - } } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/TransferOrder.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/TransferOrder.java index 9293852da..43c473464 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/TransferOrder.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/TransferOrder.java @@ -1,5 +1,8 @@ package org.dromara.daxpay.unisdk.common.bean; +import lombok.Getter; +import lombok.Setter; + import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; @@ -18,68 +21,96 @@ public class TransferOrder implements Order { /** * 转账批次订单单号 */ + @Setter + @Getter private String batchNo; /** * 转账订单单号 */ + @Setter + @Getter private String outNo; /** * 收款方账户, 用户openid,卡号等等 */ + @Setter + @Getter private String payeeAccount; /** * 转账金额 */ + @Setter + @Getter private BigDecimal amount; /** * 付款人名称 */ + @Setter + @Getter private String payerName; /** * 收款人名称 */ + @Setter + @Getter private String payeeName; /** * 收款人地址 */ + @Setter + @Getter private String payeeAddress; /** * 备注 */ + @Setter + @Getter private String remark; /** * 收款开户行 */ + @Setter + @Getter private Bank bank; /** * 收款开户行地址 */ + @Setter + @Getter private String payeeBankAddress; /** * 币种 */ + @Setter + @Getter private CurType curType; /** * 国家代码 */ + @Setter + @Getter private CountryCode countryCode; /** * 转账类型,收款方账户类型,比如支付宝账户或者银行卡 */ + @Setter + @Getter private TransferType transferType; /** * 操作者ip,根据支付平台所需进行设置 */ + @Setter + @Getter private String ip; @@ -88,118 +119,6 @@ public class TransferOrder implements Order { */ private Map attr; - public String getBatchNo() { - return batchNo; - } - - public void setBatchNo(String batchNo) { - this.batchNo = batchNo; - } - - public String getOutNo() { - return outNo; - } - - public void setOutNo(String outNo) { - this.outNo = outNo; - } - - public String getPayeeAccount() { - return payeeAccount; - } - - public void setPayeeAccount(String payeeAccount) { - this.payeeAccount = payeeAccount; - } - - public BigDecimal getAmount() { - return amount; - } - - public void setAmount(BigDecimal amount) { - this.amount = amount; - } - - public String getPayerName() { - return payerName; - } - - public void setPayerName(String payerName) { - this.payerName = payerName; - } - - public String getPayeeName() { - return payeeName; - } - - public void setPayeeName(String payeeName) { - this.payeeName = payeeName; - } - - public String getPayeeAddress() { - return payeeAddress; - } - - public void setPayeeAddress(String payeeAddress) { - this.payeeAddress = payeeAddress; - } - - public String getRemark() { - return remark; - } - - public void setRemark(String remark) { - this.remark = remark; - } - - public Bank getBank() { - return bank; - } - - public void setBank(Bank bank) { - this.bank = bank; - } - - public String getPayeeBankAddress() { - return payeeBankAddress; - } - - public void setPayeeBankAddress(String payeeBankAddress) { - this.payeeBankAddress = payeeBankAddress; - } - - public CountryCode getCountryCode() { - return countryCode; - } - - public void setCountryCode(CountryCode countryCode) { - this.countryCode = countryCode; - } - - public CurType getCurType() { - return curType; - } - - public void setCurType(CurType curType) { - this.curType = curType; - } - - public TransferType getTransferType() { - return transferType; - } - - public void setTransferType(TransferType transferType) { - this.transferType = transferType; - } - - public String getIp() { - return ip; - } - - public void setIp(String ip) { - this.ip = ip; - } - @Override public Map getAttrs() { if (null == attr) { diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/outbuilder/JsonBuilder.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/outbuilder/JsonBuilder.java index b163cd548..6262ed2f1 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/outbuilder/JsonBuilder.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/outbuilder/JsonBuilder.java @@ -2,6 +2,7 @@ package org.dromara.daxpay.unisdk.common.bean.outbuilder; import com.alibaba.fastjson.JSONObject; +import lombok.Getter; import org.dromara.daxpay.unisdk.common.bean.PayOutMessage; /** @@ -11,6 +12,7 @@ import org.dromara.daxpay.unisdk.common.bean.PayOutMessage; * date 2017/1/13 14:30 * */ +@Getter public class JsonBuilder extends BaseBuilder{ JSONObject json = null; @@ -23,10 +25,6 @@ public class JsonBuilder extends BaseBuilder{ return this; } - public JSONObject getJson() { - return json; - } - @Override public PayOutMessage build() { PayJsonOutMessage message = new PayJsonOutMessage(); diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/outbuilder/PayXmlOutMessage.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/outbuilder/PayXmlOutMessage.java index 6bd62b712..f222545e3 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/outbuilder/PayXmlOutMessage.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/bean/outbuilder/PayXmlOutMessage.java @@ -1,5 +1,7 @@ package org.dromara.daxpay.unisdk.common.bean.outbuilder; +import lombok.Getter; +import lombok.Setter; import org.dromara.daxpay.unisdk.common.bean.PayOutMessage; /** @@ -9,6 +11,8 @@ import org.dromara.daxpay.unisdk.common.bean.PayOutMessage; * date 2016-6-1 13:53:3 * */ +@Setter +@Getter public class PayXmlOutMessage extends PayOutMessage{ private String code; @@ -16,14 +20,6 @@ public class PayXmlOutMessage extends PayOutMessage{ public PayXmlOutMessage() { } - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - @Override public String toMessage() { return " */ public class PayException implements PayError { - private String errorCode; - private String errorMsg; + private final String errorCode; + private final String errorMsg; private String content; @Override diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/ClientHttpRequest.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/ClientHttpRequest.java index d28254cc2..f70798566 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/ClientHttpRequest.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/ClientHttpRequest.java @@ -3,6 +3,8 @@ package org.dromara.daxpay.unisdk.common.http; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; import org.dromara.daxpay.unisdk.common.bean.MethodType; import org.dromara.daxpay.unisdk.common.bean.result.PayException; import org.dromara.daxpay.unisdk.common.exception.PayErrorException; @@ -35,6 +37,7 @@ import static org.dromara.daxpay.unisdk.common.http.UriVariables.getMapToParamet * date 2017/3/4 17:56 * */ +@Slf4j public class ClientHttpRequest extends HttpEntityEnclosingRequestBase implements org.apache.http.client.ResponseHandler { protected static final Logger LOG = LoggerFactory.getLogger(ClientHttpRequest.class); public static final ContentType APPLICATION_FORM_URLENCODED_UTF_8 = ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8); @@ -43,11 +46,19 @@ public class ClientHttpRequest extends HttpEntityEnclosingRequestBase impleme /** * http请求方式 get pos + * -- SETTER -- + * 设置请求方式 + * + * @param method 请求方式 + * {@link MethodType} 请求方式 + */ + @Setter private MethodType method; /** * 默认使用的响应编码 */ + @Setter private Charset defaultCharset; /** * 响应类型 @@ -161,16 +172,6 @@ public class ClientHttpRequest extends HttpEntityEnclosingRequestBase impleme setParameters(request); } - /** - * 设置请求方式 - * - * @param method 请求方式 - * {@link org.dromara.daxpay.unisdk.common.bean.MethodType} 请求方式 - */ - public void setMethod(MethodType method) { - this.method = method; - } - /** * 获取请求方式 * @@ -188,10 +189,6 @@ public class ClientHttpRequest extends HttpEntityEnclosingRequestBase impleme return defaultCharset; } - public void setDefaultCharset(Charset defaultCharset) { - this.defaultCharset = defaultCharset; - } - /** * 设置代理 * @@ -214,54 +211,57 @@ public class ClientHttpRequest extends HttpEntityEnclosingRequestBase impleme * @return 当前HTTP请求的客户端 */ public ClientHttpRequest setParameters(Object request) { - if (null == request) { - return this; - } - if (request instanceof HttpHeader) { - HttpHeader entity = (HttpHeader) request; - if (null != entity.getHeaders()) { - if (LOG.isDebugEnabled()) { - LOG.debug("header : " + JSON.toJSONString(entity.getHeaders())); - } - for (Header header : entity.getHeaders()) { - addHeader(header); + switch (request) { + case null -> { + return this; + } + case HttpHeader entity -> { + if (null != entity.getHeaders()) { + if (log.isDebugEnabled()) { + log.debug("header : " + JSON.toJSONString(entity.getHeaders())); + } + for (Header header : entity.getHeaders()) { + addHeader(header); + } } } - } else if (request instanceof HttpStringEntity) { - HttpStringEntity entity = (HttpStringEntity) request; - if (!entity.isEmpty()) { + case HttpStringEntity entity -> { + if (!entity.isEmpty()) { + setEntity(entity); + } + if (null != entity.getHeaders()) { + if (log.isDebugEnabled()) { + log.debug("header : " + JSON.toJSONString(entity.getHeaders())); + } + for (Header header : entity.getHeaders()) { + addHeader(header); + } + } + } + case HttpEntity httpEntity -> setEntity(httpEntity); + case Map map -> { + String parameters = getMapToParameters(map); + if (log.isDebugEnabled()) { + log.debug("Parameter : " + parameters); + } + StringEntity entity = new StringEntity(parameters, APPLICATION_FORM_URLENCODED_UTF_8); setEntity(entity); } - if (null != entity.getHeaders()) { - if (LOG.isDebugEnabled()) { - LOG.debug("header : " + JSON.toJSONString(entity.getHeaders())); + case String s -> { + if (log.isDebugEnabled()) { + log.debug("Parameter : " + request); } - for (Header header : entity.getHeaders()) { - addHeader(header); + StringEntity entity = new StringEntity(s, APPLICATION_FORM_URLENCODED_UTF_8); + setEntity(entity); + } + default -> { + String body = JSON.toJSONString(request); + if (log.isDebugEnabled()) { + log.debug("body : " + request); } + StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON); + setEntity(entity); } - } else if (request instanceof HttpEntity) { - setEntity((HttpEntity) request); - } else if (request instanceof Map) { - String parameters = getMapToParameters((Map) request); - if (LOG.isDebugEnabled()) { - LOG.debug("Parameter : " + parameters); - } - StringEntity entity = new StringEntity(parameters, APPLICATION_FORM_URLENCODED_UTF_8); - setEntity(entity); - } else if (request instanceof String) { - if (LOG.isDebugEnabled()) { - LOG.debug("Parameter : " + request); - } - StringEntity entity = new StringEntity((String) request, APPLICATION_FORM_URLENCODED_UTF_8); - setEntity(entity); - } else { - String body = JSON.toJSONString(request); - if (LOG.isDebugEnabled()) { - LOG.debug("body : " + request); - } - StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON); - setEntity(entity); } return this; @@ -351,8 +351,8 @@ public class ClientHttpRequest extends HttpEntityEnclosingRequestBase impleme //获取响应的文本内容 String result = EntityUtils.toString(entity, getDefaultCharset()); - if (LOG.isDebugEnabled()) { - LOG.debug("请求响应内容:\r\n" + result); + if (log.isDebugEnabled()) { + log.debug("请求响应内容:\r\n{}", result); } if (responseType.isAssignableFrom(String.class)) { return (T) result; @@ -395,7 +395,7 @@ public class ClientHttpRequest extends HttpEntityEnclosingRequestBase impleme * @return 布尔型, true为json内容类型 */ private boolean isJson(String contentType, String textFirst) { - return (ContentType.APPLICATION_JSON.getMimeType().equals(contentType) || "{[".indexOf(textFirst) >= 0); + return (ContentType.APPLICATION_JSON.getMimeType().equals(contentType) || "{[".contains(textFirst)); } /** @@ -416,7 +416,7 @@ public class ClientHttpRequest extends HttpEntityEnclosingRequestBase impleme * @return 布尔型, true为xml内容类型 */ private boolean isXml(String contentType, String textFirst) { - return (ContentType.APPLICATION_XML.getMimeType().equals(contentType) || "<".indexOf(textFirst) >= 0); + return (ContentType.APPLICATION_XML.getMimeType().equals(contentType) || "<".contains(textFirst)); } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpConfigStorage.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpConfigStorage.java index 28f2bbd82..e6139e7e0 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpConfigStorage.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpConfigStorage.java @@ -1,6 +1,8 @@ package org.dromara.daxpay.unisdk.common.http; +import lombok.Getter; +import lombok.Setter; import org.dromara.daxpay.unisdk.common.bean.CertStoreType; import java.io.IOException; @@ -14,22 +16,47 @@ import java.io.InputStream; * date 2017/3/3 20:48 * */ +@Getter public class HttpConfigStorage { /** * http代理地址 + * -- GETTER -- + * http代理地址 + * + * @return http代理地址 + */ + @Setter private String httpProxyHost; /** * 代理端口 + * -- GETTER -- + * 代理端口 + * + * @return 代理端口 + */ + @Setter private int httpProxyPort; /** * 请求授权用户名 + * -- GETTER -- + * 请求授权用户名 + * + * @return 用户名 + */ + @Setter private String authUsername; /** * 请求授权密码 + * -- GETTER -- + * 请求授权密码 + * + * @return 密码 + */ + @Setter private String authPassword; @@ -37,90 +64,51 @@ public class HttpConfigStorage { * 证书存储类型 * @see #keystore 是否为https请求所需的证书(PKCS12)的地址,默认为地址,否则为证书信息串,文件流 */ + @Setter private CertStoreType certStoreType = CertStoreType.PATH; /** * https请求所需的证书(PKCS12) * 证书内容 + * -- GETTER -- + * 获取证书信息 + * + * @return 证书信息 根据 {@link #getCertStoreType()}进行区别地址与信息串 + */ private Object keystore; /** * 证书对应的密码 + * -- GETTER -- + * 证书对应的密码 + * + * @return 密码 + */ + @Setter private String storePassword; /** * 最大连接数 */ + @Setter private int maxTotal = 0; /** * 默认的每个路由的最大连接数 */ + @Setter private int defaultMaxPerRoute = 0; /** * 默认使用的响应编码 */ + @Setter private String charset; + @Setter private int socketTimeout = -1; + @Setter private int connectTimeout = -1; - /** - * http代理地址 - * @return http代理地址 - */ - public String getHttpProxyHost() { - return httpProxyHost; - } - - - public void setHttpProxyHost(String httpProxyHost) { - this.httpProxyHost = httpProxyHost; - } - - /** - * 代理端口 - * @return 代理端口 - */ - public int getHttpProxyPort() { - return httpProxyPort; - } - - public void setHttpProxyPort(int httpProxyPort) { - this.httpProxyPort = httpProxyPort; - } - - /** - * 请求授权用户名 - * @return 用户名 - */ - public String getAuthUsername() { - return authUsername; - } - - public void setAuthUsername(String authUsername) { - this.authUsername = authUsername; - } - /** - * 请求授权密码 - * @return 密码 - */ - public String getAuthPassword() { - return authPassword; - } - - public void setAuthPassword(String authPassword) { - this.authPassword = authPassword; - } - - - public CertStoreType getCertStoreType() { - return certStoreType; - } - - public void setCertStoreType(CertStoreType certStoreType) { - this.certStoreType = certStoreType; - } /** * 获取证书信息 @@ -133,13 +121,7 @@ public class HttpConfigStorage { } return certStoreType.getInputStream(keystore); } - /** - * 获取证书信息 - * @return 证书信息 根据 {@link #getCertStoreType()}进行区别地址与信息串 - */ - public Object getKeystore() { - return keystore; - } + /** * 获取证书信息 证书地址 * @return 证书信息 根据 {@link #getCertStoreType()}进行区别地址与信息串 @@ -163,55 +145,4 @@ public class HttpConfigStorage { this.keystore = keystore; } - /** - * 证书对应的密码 - * @return 密码 - */ - public String getStorePassword() { - return storePassword; - } - - public void setStorePassword(String storePassword) { - this.storePassword = storePassword; - } - - public int getMaxTotal() { - return maxTotal; - } - - public void setMaxTotal(int maxTotal) { - this.maxTotal = maxTotal; - } - - public int getDefaultMaxPerRoute() { - return defaultMaxPerRoute; - } - - public void setDefaultMaxPerRoute(int defaultMaxPerRoute) { - this.defaultMaxPerRoute = defaultMaxPerRoute; - } - - public String getCharset() { - return charset; - } - - public void setCharset(String charset) { - this.charset = charset; - } - - public int getSocketTimeout() { - return socketTimeout; - } - - public void setSocketTimeout(int socketTimeout) { - this.socketTimeout = socketTimeout; - } - - public int getConnectTimeout() { - return connectTimeout; - } - - public void setConnectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - } } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpHeader.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpHeader.java index 5175f9029..e5bec915e 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpHeader.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpHeader.java @@ -1,5 +1,7 @@ package org.dromara.daxpay.unisdk.common.http; +import lombok.Getter; +import lombok.Setter; import org.apache.http.Header; import org.apache.http.message.BasicHeader; @@ -17,9 +19,21 @@ import java.util.Map; * date 2018/01/30 * */ +@Setter +@Getter public class HttpHeader{ /** * 请求头 + * -- GETTER -- + * 获取请求头集 + * + * + * -- SETTER -- + * 设置请求头集 + * + @return 请求头集 + * @param headers 请求头集 + */ private List
headers; @@ -39,15 +53,6 @@ public class HttpHeader{ addHeader(header); } - /** - * 获取请求头集 - * - * @return 请求头集 - */ - public List
getHeaders() { - return headers; - } - /** * 添加请求头 * @@ -60,15 +65,6 @@ public class HttpHeader{ this.headers.add(header); } - /** - * 设置请求头集 - * - * @param headers 请求头集 - */ - public void setHeaders(List
headers) { - this.headers = headers; - } - /** * 设置请求头集 * diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpRequestTemplate.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpRequestTemplate.java index 9cc324de2..0d25e2a2c 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpRequestTemplate.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpRequestTemplate.java @@ -1,9 +1,7 @@ package org.dromara.daxpay.unisdk.common.http; -import org.dromara.daxpay.unisdk.common.bean.MethodType; -import org.dromara.daxpay.unisdk.common.bean.result.PayException; -import org.dromara.daxpay.unisdk.common.exception.PayErrorException; -import org.dromara.daxpay.unisdk.common.util.str.StringUtils; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; @@ -22,8 +20,10 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContexts; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.dromara.daxpay.unisdk.common.bean.MethodType; +import org.dromara.daxpay.unisdk.common.bean.result.PayException; +import org.dromara.daxpay.unisdk.common.exception.PayErrorException; +import org.dromara.daxpay.unisdk.common.util.str.StringUtils; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; @@ -44,29 +44,26 @@ import java.util.Map; * date 2017/3/3 21:33 * */ +@Slf4j public class HttpRequestTemplate { - protected static final Logger LOG = LoggerFactory.getLogger(HttpRequestTemplate.class); - protected CloseableHttpClient httpClient; protected PoolingHttpClientConnectionManager connectionManager; + /** + * -- GETTER -- + * 获取代理带代理地址的 HttpHost + * + * @return 获取代理带代理地址的 HttpHost + */ + @Getter protected HttpHost httpProxy; protected HttpConfigStorage configStorage; private SSLConnectionSocketFactory sslsf; - /** - * 获取代理带代理地址的 HttpHost - * - * @return 获取代理带代理地址的 HttpHost - */ - public HttpHost getHttpProxy() { - return httpProxy; - } - public CloseableHttpClient getHttpClient() { if (null != httpClient) { return httpClient; @@ -93,12 +90,12 @@ public class HttpRequestTemplate { } private RequestConfig createRequestConfig(HttpConfigStorage configStorage) { - RequestConfig requestConfig = RequestConfig.custom() + // .setConnectionRequestTimeout(1000) + return RequestConfig.custom() .setSocketTimeout(configStorage.getSocketTimeout()) .setConnectTimeout(configStorage.getConnectTimeout()) // .setConnectionRequestTimeout(1000) .build(); - return requestConfig; } /** @@ -130,7 +127,7 @@ public class HttpRequestTemplate { return sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault()); } catch (NoSuchAlgorithmException e) { - LOG.error("", e); + log.error("", e); } } @@ -156,11 +153,8 @@ public class HttpRequestTemplate { return sslsf; } - catch (IOException e) { - LOG.error("", e); - } - catch (GeneralSecurityException e) { - LOG.error("", e); + catch (IOException | GeneralSecurityException e) { + log.error("", e); } return null; @@ -202,8 +196,8 @@ public class HttpRequestTemplate { if (0 == configStorage.getMaxTotal() || 0 == configStorage.getDefaultMaxPerRoute()) { return null; } - if (LOG.isInfoEnabled()) { - LOG.info(String.format("Initialize the PoolingHttpClientConnectionManager -- maxTotal:%s, defaultMaxPerRoute:%s", configStorage.getMaxTotal(), configStorage.getDefaultMaxPerRoute())); + if (log.isInfoEnabled()) { + log.info(String.format("Initialize the PoolingHttpClientConnectionManager -- maxTotal:%s, defaultMaxPerRoute:%s", configStorage.getMaxTotal(), configStorage.getDefaultMaxPerRoute())); } Registry socketFactoryRegistry = RegistryBuilder.create() .register("https", createSSL(configStorage)) @@ -429,8 +423,8 @@ public class HttpRequestTemplate { */ public ResponseEntity doExecuteEntity(URI uri, Object request, Class responseType, MethodType method) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("uri:%s, httpMethod:%s ", uri, method.name())); + if (log.isDebugEnabled()) { + log.debug(String.format("uri:%s, httpMethod:%s ", uri, method.name())); } ClientHttpRequest httpRequest = new ClientHttpRequest(uri, method, request, null == configStorage ? null : configStorage.getCharset()); //判断是否有代理设置 diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpStringEntity.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpStringEntity.java index dbc3262e0..5a7283708 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpStringEntity.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/HttpStringEntity.java @@ -1,10 +1,11 @@ package org.dromara.daxpay.unisdk.common.http; -import org.dromara.daxpay.unisdk.common.util.str.StringUtils; +import lombok.Getter; import org.apache.http.Header; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHeader; +import org.dromara.daxpay.unisdk.common.util.str.StringUtils; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; @@ -28,7 +29,18 @@ import static org.dromara.daxpay.unisdk.common.http.UriVariables.getMapToParamet public class HttpStringEntity extends StringEntity { /** * 请求头 + * -- GETTER -- + * 获取请求头集 + * + * + * -- SETTER -- + * 设置请求头集 + * + @return 请求头集 + * @param headers 请求头集 + */ + @Getter private List
headers; /** * 是否为空的请求实体 @@ -195,15 +207,6 @@ public class HttpStringEntity extends StringEntity { } } - /** - * 获取请求头集 - * - * @return 请求头集 - */ - public List
getHeaders() { - return headers; - } - /** * 添加请求头 * @@ -216,15 +219,6 @@ public class HttpStringEntity extends StringEntity { this.headers.add(header); } - /** - * 设置请求头集 - * - * @param headers 请求头集 - */ - public void setHeaders(List
headers) { - this.headers = headers; - } - /** * 设置请求头集 * diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/ResponseEntity.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/ResponseEntity.java index 2a9b0103f..0c7e11ca3 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/ResponseEntity.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/ResponseEntity.java @@ -1,5 +1,6 @@ package org.dromara.daxpay.unisdk.common.http; +import lombok.Getter; import org.apache.http.Header; /** @@ -8,6 +9,7 @@ import org.apache.http.Header; * email egzosn@gmail.com * date 2021/8/1 */ +@Getter public class ResponseEntity { private final int statusCode; private final Header[] headers; @@ -19,15 +21,4 @@ public class ResponseEntity { this.body = body; } - public int getStatusCode() { - return statusCode; - } - - public Header[] getHeaders() { - return headers; - } - - public T getBody() { - return body; - } } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/UriVariables.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/UriVariables.java index bcc40e776..c8e5a41c3 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/UriVariables.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/http/UriVariables.java @@ -105,17 +105,16 @@ public final class UriVariables { if (o instanceof List) { o = ((List) o).toArray(); } - if (o instanceof Object[]) { - Object[] os = (Object[]) o; - String valueStr = ""; + if (o instanceof Object[] os) { + StringBuilder valueStr = new StringBuilder(); for (int i = 0, len = os.length; i < len; i++) { if (null == os[i]) { continue; } String value = os[i].toString().trim(); - valueStr += (i == len - 1) ? value : value + ","; + valueStr.append((i == len - 1) ? value : value + ","); } - builder.append(entry.getKey()).append("=").append(urlEncoder(valueStr)).append("&"); + builder.append(entry.getKey()).append("=").append(urlEncoder(valueStr.toString())).append("&"); continue; } builder.append(entry.getKey()).append("=").append(urlEncoder(entry.getValue().toString())).append("&"); @@ -216,7 +215,7 @@ public final class UriVariables { return URLEncoder.encode(str, enc); } catch (UnsupportedEncodingException e) { - LOG.error("", e); + log.error("", e); } return str; } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/DateUtils.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/DateUtils.java index 1550e42e4..829be1555 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/DateUtils.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/DateUtils.java @@ -1,8 +1,7 @@ package org.dromara.daxpay.unisdk.common.util; +import lombok.extern.slf4j.Slf4j; import org.apache.http.util.Args; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.lang.ref.SoftReference; import java.text.ParseException; @@ -21,8 +20,8 @@ import java.util.TimeZone; * date 2018-11-21 16:43:20 * */ +@Slf4j public final class DateUtils { - private static final Logger LOG = LoggerFactory.getLogger(DateUtils.class); private DateUtils() { } @@ -83,7 +82,7 @@ public final class DateUtils { return formatFor.parse(date); } catch (ParseException e) { - LOG.error("", e); + log.error("", e); } return null; } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/IOUtils.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/IOUtils.java deleted file mode 100644 index cc48d1878..000000000 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/IOUtils.java +++ /dev/null @@ -1,2385 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.dromara.daxpay.unisdk.common.util; - -import org.apache.commons.codec.Charsets; - -import java.io.*; -import java.net.*; -import java.nio.channels.Selector; -import java.nio.charset.Charset; -import java.nio.charset.UnsupportedCharsetException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * General IO stream manipulation utilities. - *

- * This class provides static utility methods for input/output operations. - *

    - *
  • closeQuietly - these methods close a stream ignoring nulls and exceptions - *
  • toXxx/read - these methods read data from a stream - *
  • write - these methods write data to a stream - *
  • copy - these methods copy all the data from one stream to another - *
  • contentEquals - these methods compare the content of two streams - *
- *

- * The byte-to-char methods and char-to-byte methods involve a conversion step. - * Two methods are provided in each case, one that uses the platform default - * encoding and the other which allows you to specify an encoding. You are - * encouraged to always specify an encoding because relying on the platform - * default can lead to unexpected results, for example when moving from - * development to production. - *

- * All the methods in this class that read a stream are buffered internally. - * This means that there is no cause to use a BufferedInputStream - * or BufferedReader. The default buffer size of 4K has been shown - * to be efficient in tests. - *

- * Wherever possible, the methods in this class do not flush or close - * the stream. This is to avoid making non-portable assumptions about the - * streams' origin and further use. Thus the caller is still responsible for - * closing streams after use. - *

- * Origin of code: Excalibur. - * - * @version $Id: IOUtils.java 1326636 2012-04-16 14:54:53Z ggregory $ - */ -public class IOUtils { - // NOTE: This class is focussed on InputStream, OutputStream, Reader and - // Writer. Each method should take at least one of these as a parameter, - // or return one of them. - - private static final int EOF = -1; - /** - * The system line separator string. - */ - public static final String LINE_SEPARATOR; - - static { - // avoid security issues - StringWriter buf = new StringWriter(4); - PrintWriter out = new PrintWriter(buf); - out.println(); - LINE_SEPARATOR = buf.toString(); - out.close(); - } - - /** - * The default buffer size ({@value}) to use for - * {@link #copyLarge(InputStream, OutputStream)} - * and - * {@link #copyLarge(Reader, Writer)} - */ - private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; - - /** - * The default buffer size to use for the skip() methods. - */ - private static final int SKIP_BUFFER_SIZE = 2048; - - // Allocated in the relevant skip method if necessary. - /* - * N.B. no need to synchronize these because: - * - we don't care if the buffer is created multiple times (the data is ignored) - * - we always use the same size buffer, so if it it is recreated it will still be OK - * (if the buffer size were variable, we would need to synch. to ensure some other thread - * did not create a smaller one) - */ - private static char[] SKIP_CHAR_BUFFER; - private static byte[] SKIP_BYTE_BUFFER; - - /** - * Instances should NOT be constructed in standard programming. - */ - public IOUtils() { - super(); - } - - //----------------------------------------------------------------------- - - /** - * Closes a URLConnection. - * - * @param conn the connection to close. - * @since 2.4 - */ - public static void close(URLConnection conn) { - if (conn instanceof HttpURLConnection) { - ((HttpURLConnection) conn).disconnect(); - } - } - - /** - * Unconditionally close an Reader. - *

- * Equivalent to {@link Reader#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   char[] data = new char[1024];
-     *   Reader in = null;
-     *   try {
-     *       in = new FileReader("foo.txt");
-     *       in.read(data);
-     *       in.close(); //close errors are handled
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(in);
-     *   }
-     * 
- * - * @param input the Reader to close, may be null or already closed - */ - public static void closeQuietly(Reader input) { - closeQuietly((Closeable) input); - } - - /** - * Unconditionally close a Writer. - *

- * Equivalent to {@link Writer#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   Writer out = null;
-     *   try {
-     *       out = new StringWriter();
-     *       out.write("Hello World");
-     *       out.close(); //close errors are handled
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(out);
-     *   }
-     * 
- * - * @param output the Writer to close, may be null or already closed - */ - public static void closeQuietly(Writer output) { - closeQuietly((Closeable) output); - } - - /** - * Unconditionally close an InputStream. - *

- * Equivalent to {@link InputStream#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   byte[] data = new byte[1024];
-     *   InputStream in = null;
-     *   try {
-     *       in = new FileInputStream("foo.txt");
-     *       in.read(data);
-     *       in.close(); //close errors are handled
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(in);
-     *   }
-     * 
- * - * @param input the InputStream to close, may be null or already closed - */ - public static void closeQuietly(InputStream input) { - closeQuietly((Closeable) input); - } - - /** - * Unconditionally close an OutputStream. - *

- * Equivalent to {@link OutputStream#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     * byte[] data = "Hello, World".getBytes();
-     *
-     * OutputStream out = null;
-     * try {
-     *     out = new FileOutputStream("foo.txt");
-     *     out.write(data);
-     *     out.close(); //close errors are handled
-     * } catch (IOException e) {
-     *     // error handling
-     * } finally {
-     *     IOUtils.closeQuietly(out);
-     * }
-     * 
- * - * @param output the OutputStream to close, may be null or already closed - */ - public static void closeQuietly(OutputStream output) { - closeQuietly((Closeable) output); - } - - /** - * Unconditionally close a Closeable. - *

- * Equivalent to {@link Closeable#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   Closeable closeable = null;
-     *   try {
-     *       closeable = new FileReader("foo.txt");
-     *       // process closeable
-     *       closeable.close();
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(closeable);
-     *   }
-     * 
- * - * @param closeable the object to close, may be null or already closed - * @since 2.0 - */ - public static void closeQuietly(Closeable closeable) { - try { - if (closeable != null) { - closeable.close(); - } - } catch (IOException ioe) { - // ignore - } - } - - /** - * Unconditionally close a Socket. - *

- * Equivalent to {@link Socket#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   Socket socket = null;
-     *   try {
-     *       socket = new Socket("http://www.foo.com/", 80);
-     *       // process socket
-     *       socket.close();
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(socket);
-     *   }
-     * 
- * - * @param sock the Socket to close, may be null or already closed - * @since 2.0 - */ - public static void closeQuietly(Socket sock) { - if (sock != null) { - try { - sock.close(); - } catch (IOException ioe) { - // ignored - } - } - } - - /** - * Unconditionally close a Selector. - *

- * Equivalent to {@link Selector#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   Selector selector = null;
-     *   try {
-     *       selector = Selector.open();
-     *       // process socket
-     *
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(selector);
-     *   }
-     * 
- * - * @param selector the Selector to close, may be null or already closed - * @since 2.2 - */ - public static void closeQuietly(Selector selector) { - if (selector != null) { - try { - selector.close(); - } catch (IOException ioe) { - // ignored - } - } - } - - /** - * Unconditionally close a ServerSocket. - *

- * Equivalent to {@link ServerSocket#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   ServerSocket socket = null;
-     *   try {
-     *       socket = new ServerSocket();
-     *       // process socket
-     *       socket.close();
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(socket);
-     *   }
-     * 
- * - * @param sock the ServerSocket to close, may be null or already closed - * @since 2.2 - */ - public static void closeQuietly(ServerSocket sock) { - if (sock != null) { - try { - sock.close(); - } catch (IOException ioe) { - // ignored - } - } - } - - /** - * Fetches entire contents of an InputStream and represent - * same data as result InputStream. - *

- * This method is useful where, - *

    - *
  • Source InputStream is slow.
  • - *
  • It has network resources associated, so we cannot keep it open for - * long time.
  • - *
  • It has network timeout associated.
  • - *
- * It can be used in favor of {@link #toByteArray(InputStream)}, since it - * avoids unnecessary allocation and copy of byte[].
- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input Stream to be fully buffered. - * @return A fully buffered stream. - * @since 2.0 - */ - public static InputStream toBufferedInputStream(InputStream input) { - return new BufferedInputStream(input); - } - - /** - * Returns the given reader if it is a {@link BufferedReader}, otherwise creates a toBufferedReader for the given - * reader. - * - * @param reader the reader to wrap or return - * @return the given reader or a new {@link BufferedReader} for the given reader - * @since 2.2 - */ - public static BufferedReader toBufferedReader(Reader reader) { - return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); - } - - // read toByteArray - //----------------------------------------------------------------------- - - /** - * Get the contents of an InputStream as a byte[]. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input the InputStream to read from - * @return the requested byte array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - */ - public static byte[] toByteArray(InputStream input) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy(input, output); - return output.toByteArray(); - } - - /** - * Get contents of an InputStream as a byte[]. - * Use this method instead of toByteArray(InputStream) - * when InputStream size is known. - * NOTE: the method checks that the length can safely be cast to an int without truncation - * before using {@link IOUtils#toByteArray(InputStream, int)} to read into the byte array. - * (Arrays can have no more than Integer.MAX_VALUE entries anyway) - * - * @param input the InputStream to read from - * @param size the size of InputStream - * @return the requested byte array - * @throws IOException if an I/O error occurs or InputStream size differ from parameter size - * @throws IllegalArgumentException if size is less than zero or size is greater than Integer.MAX_VALUE - * @see IOUtils#toByteArray(InputStream, int) - * @since 2.1 - */ - public static byte[] toByteArray(InputStream input, long size) throws IOException { - - if (size > Integer.MAX_VALUE) { - throw new IllegalArgumentException("Size cannot be greater than Integer max value: " + size); - } - - return toByteArray(input, (int) size); - } - - /** - * Get the contents of an InputStream as a byte[]. - * Use this method instead of toByteArray(InputStream) - * when InputStream size is known - * - * @param input the InputStream to read from - * @param size the size of InputStream - * @return the requested byte array - * @throws IOException if an I/O error occurs or InputStream size differ from parameter size - * @throws IllegalArgumentException if size is less than zero - * @since 2.1 - */ - public static byte[] toByteArray(InputStream input, int size) throws IOException { - - if (size < 0) { - throw new IllegalArgumentException("Size must be equal or greater than zero: " + size); - } - - if (size == 0) { - return new byte[0]; - } - - byte[] data = new byte[size]; - int offset = 0; - int readed; - - while (offset < size && (readed = input.read(data, offset, size - offset)) != EOF) { - offset += readed; - } - - if (offset != size) { - throw new IOException("Unexpected readed size. current: " + offset + ", excepted: " + size); - } - - return data; - } - - /** - * Get the contents of a Reader as a byte[] - * using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input the Reader to read from - * @return the requested byte array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - */ - public static byte[] toByteArray(Reader input) throws IOException { - return toByteArray(input, Charset.defaultCharset()); - } - - /** - * Get the contents of a Reader as a byte[] - * using the specified character encoding. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input the Reader to read from - * @param encoding the encoding to use, null means platform default - * @return the requested byte array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 2.3 - */ - public static byte[] toByteArray(Reader input, Charset encoding) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy(input, output, encoding); - return output.toByteArray(); - } - - /** - * Get the contents of a Reader as a byte[] - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input the Reader to read from - * @param encoding the encoding to use, null means platform default - * @return the requested byte array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 1.1 - */ - public static byte[] toByteArray(Reader input, String encoding) throws IOException { - return toByteArray(input, Charsets.toCharset(encoding)); - } - - /** - * Get the contents of a String as a byte[] - * using the default character encoding of the platform. - *

- * This is the same as {@link String#getBytes()}. - * - * @param input the String to convert - * @return the requested byte array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs (never occurs) - * @deprecated Use {@link String#getBytes()} - */ - @Deprecated - public static byte[] toByteArray(String input) throws IOException { - return input.getBytes(); - } - - /** - * Get the contents of a URI as a byte[]. - * - * @param uri the URI to read - * @return the requested byte array - * @throws NullPointerException if the uri is null - * @throws IOException if an I/O exception occurs - * @since 2.4 - */ - public static byte[] toByteArray(URI uri) throws IOException { - return IOUtils.toByteArray(uri.toURL()); - } - - /** - * Get the contents of a URL as a byte[]. - * - * @param url the URL to read - * @return the requested byte array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O exception occurs - * @since 2.4 - */ - public static byte[] toByteArray(URL url) throws IOException { - URLConnection conn = url.openConnection(); - try { - return IOUtils.toByteArray(conn); - } finally { - close(conn); - } - } - - /** - * Get the contents of a URLConnection as a byte[]. - * - * @param urlConn the URLConnection to read - * @return the requested byte array - * @throws NullPointerException if the urlConn is null - * @throws IOException if an I/O exception occurs - * @since 2.4 - */ - public static byte[] toByteArray(URLConnection urlConn) throws IOException { - InputStream inputStream = urlConn.getInputStream(); - try { - return IOUtils.toByteArray(inputStream); - } finally { - inputStream.close(); - } - } - - // read char[] - //----------------------------------------------------------------------- - - /** - * Get the contents of an InputStream as a character array - * using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param is the InputStream to read from - * @return the requested character array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static char[] toCharArray(InputStream is) throws IOException { - return toCharArray(is, Charset.defaultCharset()); - } - - /** - * Get the contents of an InputStream as a character array - * using the specified character encoding. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param is the InputStream to read from - * @param encoding the encoding to use, null means platform default - * @return the requested character array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 2.3 - */ - public static char[] toCharArray(InputStream is, Charset encoding) - throws IOException { - CharArrayWriter output = new CharArrayWriter(); - copy(is, output, encoding); - return output.toCharArray(); - } - - /** - * Get the contents of an InputStream as a character array - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param is the InputStream to read from - * @param encoding the encoding to use, null means platform default - * @return the requested character array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 1.1 - */ - public static char[] toCharArray(InputStream is, String encoding) throws IOException { - return toCharArray(is, Charsets.toCharset(encoding)); - } - - /** - * Get the contents of a Reader as a character array. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input the Reader to read from - * @return the requested character array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static char[] toCharArray(Reader input) throws IOException { - CharArrayWriter sw = new CharArrayWriter(); - copy(input, sw); - return sw.toCharArray(); - } - - // read toString - //----------------------------------------------------------------------- - - /** - * Get the contents of an InputStream as a String - * using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input the InputStream to read from - * @return the requested String - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - */ - public static String toString(InputStream input) throws IOException { - return toString(input, Charset.defaultCharset()); - } - - /** - * Get the contents of an InputStream as a String - * using the specified character encoding. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * - * @param input the InputStream to read from - * @param encoding the encoding to use, null means platform default - * @return the requested String - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 2.3 - */ - public static String toString(InputStream input, Charset encoding) throws IOException { - StringWriter sw = new StringWriter(); - copy(input, sw, encoding); - return sw.toString(); - } - - /** - * Get the contents of an InputStream as a String - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input the InputStream to read from - * @param encoding the encoding to use, null means platform default - * @return the requested String - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - */ - public static String toString(InputStream input, String encoding) - throws IOException { - return toString(input, Charsets.toCharset(encoding)); - } - - /** - * Get the contents of a Reader as a String. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input the Reader to read from - * @return the requested String - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - */ - public static String toString(Reader input) throws IOException { - StringWriter sw = new StringWriter(); - copy(input, sw); - return sw.toString(); - } - - /** - * Gets the contents at the given URI. - * - * @param uri The URI source. - * @return The contents of the URL as a String. - * @throws IOException if an I/O exception occurs. - * @since 2.1 - */ - public static String toString(URI uri) throws IOException { - return toString(uri, Charset.defaultCharset()); - } - - /** - * Gets the contents at the given URI. - * - * @param uri The URI source. - * @param encoding The encoding name for the URL contents. - * @return The contents of the URL as a String. - * @throws IOException if an I/O exception occurs. - * @since 2.3. - */ - public static String toString(URI uri, Charset encoding) throws IOException { - return toString(uri.toURL(), Charsets.toCharset(encoding)); - } - - /** - * Gets the contents at the given URI. - * - * @param uri The URI source. - * @param encoding The encoding name for the URL contents. - * @return The contents of the URL as a String. - * @throws IOException if an I/O exception occurs. - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 2.1 - */ - public static String toString(URI uri, String encoding) throws IOException { - return toString(uri, Charsets.toCharset(encoding)); - } - - /** - * Gets the contents at the given URL. - * - * @param url The URL source. - * @return The contents of the URL as a String. - * @throws IOException if an I/O exception occurs. - * @since 2.1 - */ - public static String toString(URL url) throws IOException { - return toString(url, Charset.defaultCharset()); - } - - /** - * Gets the contents at the given URL. - * - * @param url The URL source. - * @param encoding The encoding name for the URL contents. - * @return The contents of the URL as a String. - * @throws IOException if an I/O exception occurs. - * @since 2.3 - */ - public static String toString(URL url, Charset encoding) throws IOException { - InputStream inputStream = url.openStream(); - try { - return toString(inputStream, encoding); - } finally { - inputStream.close(); - } - } - - /** - * Gets the contents at the given URL. - * - * @param url The URL source. - * @param encoding The encoding name for the URL contents. - * @return The contents of the URL as a String. - * @throws IOException if an I/O exception occurs. - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 2.1 - */ - public static String toString(URL url, String encoding) throws IOException { - return toString(url, Charsets.toCharset(encoding)); - } - - /** - * Get the contents of a byte[] as a String - * using the default character encoding of the platform. - * - * @param input the byte array to read from - * @return the requested String - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs (never occurs) - * @deprecated Use {@link String#String(byte[])} - */ - @Deprecated - public static String toString(byte[] input) throws IOException { - return new String(input); - } - - /** - * Get the contents of a byte[] as a String - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - * - * @param input the byte array to read from - * @param encoding the encoding to use, null means platform default - * @return the requested String - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs (never occurs) - */ - public static String toString(byte[] input, String encoding) throws IOException { - return new String(input, Charsets.toCharset(encoding)); - } - - // readLines - //----------------------------------------------------------------------- - - /** - * Get the contents of an InputStream as a list of Strings, - * one entry per line, using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input the InputStream to read from, not null - * @return the list of Strings, never null - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static List readLines(InputStream input) throws IOException { - return readLines(input, Charset.defaultCharset()); - } - - /** - * Get the contents of an InputStream as a list of Strings, - * one entry per line, using the specified character encoding. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input the InputStream to read from, not null - * @param encoding the encoding to use, null means platform default - * @return the list of Strings, never null - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 2.3 - */ - public static List readLines(InputStream input, Charset encoding) throws IOException { - InputStreamReader reader = new InputStreamReader(input, Charsets.toCharset(encoding)); - return readLines(reader); - } - - /** - * Get the contents of an InputStream as a list of Strings, - * one entry per line, using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input the InputStream to read from, not null - * @param encoding the encoding to use, null means platform default - * @return the list of Strings, never null - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 1.1 - */ - public static List readLines(InputStream input, String encoding) throws IOException { - return readLines(input, Charsets.toCharset(encoding)); - } - - /** - * Get the contents of a Reader as a list of Strings, - * one entry per line. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input the Reader to read from, not null - * @return the list of Strings, never null - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static List readLines(Reader input) throws IOException { - BufferedReader reader = toBufferedReader(input); - List list = new ArrayList(); - String line = reader.readLine(); - while (line != null) { - list.add(line); - line = reader.readLine(); - } - return list; - } - - - //----------------------------------------------------------------------- - - /** - * Convert the specified CharSequence to an input stream, encoded as bytes - * using the default character encoding of the platform. - * - * @param input the CharSequence to convert - * @return an input stream - * @since 2.0 - */ - public static InputStream toInputStream(CharSequence input) { - return toInputStream(input, Charset.defaultCharset()); - } - - /** - * Convert the specified CharSequence to an input stream, encoded as bytes - * using the specified character encoding. - * - * @param input the CharSequence to convert - * @param encoding the encoding to use, null means platform default - * @return an input stream - * @since 2.3 - */ - public static InputStream toInputStream(CharSequence input, Charset encoding) { - return toInputStream(input.toString(), encoding); - } - - /** - * Convert the specified CharSequence to an input stream, encoded as bytes - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - * - * @param input the CharSequence to convert - * @param encoding the encoding to use, null means platform default - * @return an input stream - * @throws IOException if the encoding is invalid - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 2.0 - */ - public static InputStream toInputStream(CharSequence input, String encoding) throws IOException { - return toInputStream(input, Charsets.toCharset(encoding)); - } - - //----------------------------------------------------------------------- - - /** - * Convert the specified string to an input stream, encoded as bytes - * using the default character encoding of the platform. - * - * @param input the string to convert - * @return an input stream - * @since 1.1 - */ - public static InputStream toInputStream(String input) { - return toInputStream(input, Charset.defaultCharset()); - } - - /** - * Convert the specified string to an input stream, encoded as bytes - * using the specified character encoding. - * - * @param input the string to convert - * @param encoding the encoding to use, null means platform default - * @return an input stream - * @since 2.3 - */ - public static InputStream toInputStream(String input, Charset encoding) { - return new ByteArrayInputStream(input.getBytes(Charsets.toCharset(encoding))); - } - - /** - * Convert the specified string to an input stream, encoded as bytes - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - * - * @param input the string to convert - * @param encoding the encoding to use, null means platform default - * @return an input stream - * @throws IOException if the encoding is invalid - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 1.1 - */ - public static InputStream toInputStream(String input, String encoding) throws IOException { - byte[] bytes = input.getBytes(Charsets.toCharset(encoding)); - return new ByteArrayInputStream(bytes); - } - - // write byte[] - //----------------------------------------------------------------------- - - /** - * Writes bytes from a byte[] to an OutputStream. - * - * @param data the byte array to write, do not modify during output, - * null ignored - * @param output the OutputStream to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(byte[] data, OutputStream output) - throws IOException { - if (data != null) { - output.write(data); - } - } - - /** - * Writes bytes from a byte[] to chars on a Writer - * using the default character encoding of the platform. - *

- * This method uses {@link String#String(byte[])}. - * - * @param data the byte array to write, do not modify during output, - * null ignored - * @param output the Writer to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(byte[] data, Writer output) throws IOException { - write(data, output, Charset.defaultCharset()); - } - - /** - * Writes bytes from a byte[] to chars on a Writer - * using the specified character encoding. - *

- * This method uses {@link String#String(byte[], String)}. - * - * @param data the byte array to write, do not modify during output, - * null ignored - * @param output the Writer to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 2.3 - */ - public static void write(byte[] data, Writer output, Charset encoding) throws IOException { - if (data != null) { - output.write(new String(data, Charsets.toCharset(encoding))); - } - } - - /** - * Writes bytes from a byte[] to chars on a Writer - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#String(byte[], String)}. - * - * @param data the byte array to write, do not modify during output, - * null ignored - * @param output the Writer to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 1.1 - */ - public static void write(byte[] data, Writer output, String encoding) throws IOException { - write(data, output, Charsets.toCharset(encoding)); - } - - // write char[] - //----------------------------------------------------------------------- - - /** - * Writes chars from a char[] to a Writer - * using the default character encoding of the platform. - * - * @param data the char array to write, do not modify during output, - * null ignored - * @param output the Writer to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(char[] data, Writer output) throws IOException { - if (data != null) { - output.write(data); - } - } - - /** - * Writes chars from a char[] to bytes on an - * OutputStream. - *

- * This method uses {@link String#String(char[])} and - * {@link String#getBytes()}. - * - * @param data the char array to write, do not modify during output, - * null ignored - * @param output the OutputStream to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(char[] data, OutputStream output) - throws IOException { - write(data, output, Charset.defaultCharset()); - } - - /** - * Writes chars from a char[] to bytes on an - * OutputStream using the specified character encoding. - *

- * This method uses {@link String#String(char[])} and - * {@link String#getBytes(String)}. - * - * @param data the char array to write, do not modify during output, - * null ignored - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 2.3 - */ - public static void write(char[] data, OutputStream output, Charset encoding) throws IOException { - if (data != null) { - output.write(new String(data).getBytes(Charsets.toCharset(encoding))); - } - } - - /** - * Writes chars from a char[] to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#String(char[])} and - * {@link String#getBytes(String)}. - * - * @param data the char array to write, do not modify during output, - * null ignored - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 1.1 - */ - public static void write(char[] data, OutputStream output, String encoding) - throws IOException { - write(data, output, Charsets.toCharset(encoding)); - } - - // write CharSequence - //----------------------------------------------------------------------- - - /** - * Writes chars from a CharSequence to a Writer. - * - * @param data the CharSequence to write, null ignored - * @param output the Writer to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 2.0 - */ - public static void write(CharSequence data, Writer output) throws IOException { - if (data != null) { - write(data.toString(), output); - } - } - - /** - * Writes chars from a CharSequence to bytes on an - * OutputStream using the default character encoding of the - * platform. - *

- * This method uses {@link String#getBytes()}. - * - * @param data the CharSequence to write, null ignored - * @param output the OutputStream to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 2.0 - */ - public static void write(CharSequence data, OutputStream output) - throws IOException { - write(data, output, Charset.defaultCharset()); - } - - /** - * Writes chars from a CharSequence to bytes on an - * OutputStream using the specified character encoding. - *

- * This method uses {@link String#getBytes(String)}. - * - * @param data the CharSequence to write, null ignored - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 2.3 - */ - public static void write(CharSequence data, OutputStream output, Charset encoding) throws IOException { - if (data != null) { - write(data.toString(), output, encoding); - } - } - - /** - * Writes chars from a CharSequence to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#getBytes(String)}. - * - * @param data the CharSequence to write, null ignored - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 2.0 - */ - public static void write(CharSequence data, OutputStream output, String encoding) throws IOException { - write(data, output, Charsets.toCharset(encoding)); - } - - // write String - //----------------------------------------------------------------------- - - /** - * Writes chars from a String to a Writer. - * - * @param data the String to write, null ignored - * @param output the Writer to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(String data, Writer output) throws IOException { - if (data != null) { - output.write(data); - } - } - - /** - * Writes chars from a String to bytes on an - * OutputStream using the default character encoding of the - * platform. - *

- * This method uses {@link String#getBytes()}. - * - * @param data the String to write, null ignored - * @param output the OutputStream to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(String data, OutputStream output) - throws IOException { - write(data, output, Charset.defaultCharset()); - } - - /** - * Writes chars from a String to bytes on an - * OutputStream using the specified character encoding. - *

- * This method uses {@link String#getBytes(String)}. - * - * @param data the String to write, null ignored - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 2.3 - */ - public static void write(String data, OutputStream output, Charset encoding) throws IOException { - if (data != null) { - output.write(data.getBytes(Charsets.toCharset(encoding))); - } - } - - /** - * Writes chars from a String to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#getBytes(String)}. - * - * @param data the String to write, null ignored - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 1.1 - */ - public static void write(String data, OutputStream output, String encoding) - throws IOException { - write(data, output, Charsets.toCharset(encoding)); - } - - // write StringBuffer - //----------------------------------------------------------------------- - - /** - * Writes chars from a StringBuffer to a Writer. - * - * @param data the StringBuffer to write, null ignored - * @param output the Writer to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - * @deprecated replaced by write(CharSequence, Writer) - */ - @Deprecated - public static void write(StringBuffer data, Writer output) - throws IOException { - if (data != null) { - output.write(data.toString()); - } - } - - /** - * Writes chars from a StringBuffer to bytes on an - * OutputStream using the default character encoding of the - * platform. - *

- * This method uses {@link String#getBytes()}. - * - * @param data the StringBuffer to write, null ignored - * @param output the OutputStream to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - * @deprecated replaced by write(CharSequence, OutputStream) - */ - @Deprecated - public static void write(StringBuffer data, OutputStream output) - throws IOException { - write(data, output, (String) null); - } - - /** - * Writes chars from a StringBuffer to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#getBytes(String)}. - * - * @param data the StringBuffer to write, null ignored - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 1.1 - * @deprecated replaced by write(CharSequence, OutputStream, String) - */ - @Deprecated - public static void write(StringBuffer data, OutputStream output, String encoding) throws IOException { - if (data != null) { - output.write(data.toString().getBytes(Charsets.toCharset(encoding))); - } - } - - // writeLines - //----------------------------------------------------------------------- - - /** - * Writes the toString() value of each item in a collection to - * an OutputStream line by line, using the default character - * encoding of the platform and the specified line ending. - * - * @param lines the lines to write, null entries produce blank lines - * @param lineEnding the line separator to use, null is system default - * @param output the OutputStream to write to, not null, not closed - * @throws NullPointerException if the output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void writeLines(Collection lines, String lineEnding, - OutputStream output) throws IOException { - writeLines(lines, lineEnding, output, Charset.defaultCharset()); - } - - /** - * Writes the toString() value of each item in a collection to - * an OutputStream line by line, using the specified character - * encoding and the specified line ending. - * - * @param lines the lines to write, null entries produce blank lines - * @param lineEnding the line separator to use, null is system default - * @param output the OutputStream to write to, not null, not closed - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if the output is null - * @throws IOException if an I/O error occurs - * @since 2.3 - */ - public static void writeLines(Collection lines, String lineEnding, OutputStream output, Charset encoding) - throws IOException { - if (lines == null) { - return; - } - if (lineEnding == null) { - lineEnding = LINE_SEPARATOR; - } - Charset cs = Charsets.toCharset(encoding); - for (Object line : lines) { - if (line != null) { - output.write(line.toString().getBytes(cs)); - } - output.write(lineEnding.getBytes(cs)); - } - } - - /** - * Writes the toString() value of each item in a collection to - * an OutputStream line by line, using the specified character - * encoding and the specified line ending. - *

- * Character encoding names can be found at - * IANA. - * - * @param lines the lines to write, null entries produce blank lines - * @param lineEnding the line separator to use, null is system default - * @param output the OutputStream to write to, not null, not closed - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if the output is null - * @throws IOException if an I/O error occurs - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 1.1 - */ - public static void writeLines(Collection lines, String lineEnding, - OutputStream output, String encoding) throws IOException { - writeLines(lines, lineEnding, output, Charsets.toCharset(encoding)); - } - - /** - * Writes the toString() value of each item in a collection to - * a Writer line by line, using the specified line ending. - * - * @param lines the lines to write, null entries produce blank lines - * @param lineEnding the line separator to use, null is system default - * @param writer the Writer to write to, not null, not closed - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void writeLines(Collection lines, String lineEnding, - Writer writer) throws IOException { - if (lines == null) { - return; - } - if (lineEnding == null) { - lineEnding = LINE_SEPARATOR; - } - for (Object line : lines) { - if (line != null) { - writer.write(line.toString()); - } - writer.write(lineEnding); - } - } - - // copy from InputStream - //----------------------------------------------------------------------- - - /** - * Copy bytes from an InputStream to an - * OutputStream. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * Large streams (over 2GB) will return a bytes copied value of - * -1 after the copy has completed since the correct - * number of bytes cannot be returned as an int. For large streams - * use the copyLarge(InputStream, OutputStream) method. - * - * @param input the InputStream to read from - * @param output the OutputStream to write to - * @return the number of bytes copied, or -1 if > Integer.MAX_VALUE - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static int copy(InputStream input, OutputStream output) throws IOException { - long count = copyLarge(input, output); - if (count > Integer.MAX_VALUE) { - return -1; - } - return (int) count; - } - - /** - * Copy bytes from a large (over 2GB) InputStream to an - * OutputStream. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}. - * - * @param input the InputStream to read from - * @param output the OutputStream to write to - * @return the number of bytes copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.3 - */ - public static long copyLarge(InputStream input, OutputStream output) - throws IOException { - return copyLarge(input, output, new byte[DEFAULT_BUFFER_SIZE]); - } - - /** - * Copy bytes from a large (over 2GB) InputStream to an - * OutputStream. - *

- * This method uses the provided buffer, so there is no need to use a - * BufferedInputStream. - *

- * - * @param input the InputStream to read from - * @param output the OutputStream to write to - * @param buffer the buffer to use for the copy - * @return the number of bytes copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static long copyLarge(InputStream input, OutputStream output, byte[] buffer) - throws IOException { - long count = 0; - int n = 0; - while (EOF != (n = input.read(buffer))) { - output.write(buffer, 0, n); - count += n; - } - return count; - } - - /** - * Copy some or all bytes from a large (over 2GB) InputStream to an - * OutputStream, optionally skipping input bytes. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}. - * - * @param input the InputStream to read from - * @param output the OutputStream to write to - * @param inputOffset : number of bytes to skip from input before copying - * -ve values are ignored - * @param length : number of bytes to copy. -ve means all - * @return the number of bytes copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static long copyLarge(InputStream input, OutputStream output, long inputOffset, long length) - throws IOException { - return copyLarge(input, output, inputOffset, length, new byte[DEFAULT_BUFFER_SIZE]); - } - - /** - * Copy some or all bytes from a large (over 2GB) InputStream to an - * OutputStream, optionally skipping input bytes. - *

- * This method uses the provided buffer, so there is no need to use a - * BufferedInputStream. - *

- * - * @param input the InputStream to read from - * @param output the OutputStream to write to - * @param inputOffset : number of bytes to skip from input before copying - * -ve values are ignored - * @param length : number of bytes to copy. -ve means all - * @param buffer the buffer to use for the copy - * @return the number of bytes copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static long copyLarge(InputStream input, OutputStream output, - final long inputOffset, final long length, byte[] buffer) throws IOException { - if (inputOffset > 0) { - skipFully(input, inputOffset); - } - if (length == 0) { - return 0; - } - final int bufferLength = buffer.length; - int bytesToRead = bufferLength; - if (length > 0 && length < bufferLength) { - bytesToRead = (int) length; - } - int read; - long totalRead = 0; - while (bytesToRead > 0 && EOF != (read = input.read(buffer, 0, bytesToRead))) { - output.write(buffer, 0, read); - totalRead += read; - if (length > 0) { // only adjust length if not reading to the end - // Note the cast must work because buffer.length is an integer - bytesToRead = (int) Math.min(length - totalRead, bufferLength); - } - } - return totalRead; - } - - /** - * Copy bytes from an InputStream to chars on a - * Writer using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * This method uses {@link InputStreamReader}. - * - * @param input the InputStream to read from - * @param output the Writer to write to - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void copy(InputStream input, Writer output) - throws IOException { - copy(input, output, Charset.defaultCharset()); - } - - /** - * Copy bytes from an InputStream to chars on a - * Writer using the specified character encoding. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * This method uses {@link InputStreamReader}. - * - * @param input the InputStream to read from - * @param output the Writer to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.3 - */ - public static void copy(InputStream input, Writer output, Charset encoding) throws IOException { - InputStreamReader in = new InputStreamReader(input, Charsets.toCharset(encoding)); - copy(in, output); - } - - /** - * Copy bytes from an InputStream to chars on a - * Writer using the specified character encoding. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link InputStreamReader}. - * - * @param input the InputStream to read from - * @param output the Writer to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 1.1 - */ - public static void copy(InputStream input, Writer output, String encoding) throws IOException { - copy(input, output, Charsets.toCharset(encoding)); - } - - // copy from Reader - //----------------------------------------------------------------------- - - /** - * Copy chars from a Reader to a Writer. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * Large streams (over 2GB) will return a chars copied value of - * -1 after the copy has completed since the correct - * number of chars cannot be returned as an int. For large streams - * use the copyLarge(Reader, Writer) method. - * - * @param input the Reader to read from - * @param output the Writer to write to - * @return the number of characters copied, or -1 if > Integer.MAX_VALUE - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static int copy(Reader input, Writer output) throws IOException { - long count = copyLarge(input, output); - if (count > Integer.MAX_VALUE) { - return -1; - } - return (int) count; - } - - /** - * Copy chars from a large (over 2GB) Reader to a Writer. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}. - * - * @param input the Reader to read from - * @param output the Writer to write to - * @return the number of characters copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.3 - */ - public static long copyLarge(Reader input, Writer output) throws IOException { - return copyLarge(input, output, new char[DEFAULT_BUFFER_SIZE]); - } - - /** - * Copy chars from a large (over 2GB) Reader to a Writer. - *

- * This method uses the provided buffer, so there is no need to use a - * BufferedReader. - *

- * - * @param input the Reader to read from - * @param output the Writer to write to - * @param buffer the buffer to be used for the copy - * @return the number of characters copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static long copyLarge(Reader input, Writer output, char[] buffer) throws IOException { - long count = 0; - int n = 0; - while (EOF != (n = input.read(buffer))) { - output.write(buffer, 0, n); - count += n; - } - return count; - } - - /** - * Copy some or all chars from a large (over 2GB) InputStream to an - * OutputStream, optionally skipping input chars. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}. - * - * @param input the Reader to read from - * @param output the Writer to write to - * @param inputOffset : number of chars to skip from input before copying - * -ve values are ignored - * @param length : number of chars to copy. -ve means all - * @return the number of chars copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static long copyLarge(Reader input, Writer output, final long inputOffset, final long length) - throws IOException { - return copyLarge(input, output, inputOffset, length, new char[DEFAULT_BUFFER_SIZE]); - } - - /** - * Copy some or all chars from a large (over 2GB) InputStream to an - * OutputStream, optionally skipping input chars. - *

- * This method uses the provided buffer, so there is no need to use a - * BufferedReader. - *

- * - * @param input the Reader to read from - * @param output the Writer to write to - * @param inputOffset : number of chars to skip from input before copying - * -ve values are ignored - * @param length : number of chars to copy. -ve means all - * @param buffer the buffer to be used for the copy - * @return the number of chars copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static long copyLarge(Reader input, Writer output, final long inputOffset, final long length, char[] buffer) - throws IOException { - if (inputOffset > 0) { - skipFully(input, inputOffset); - } - if (length == 0) { - return 0; - } - int bytesToRead = buffer.length; - if (length > 0 && length < buffer.length) { - bytesToRead = (int) length; - } - int read; - long totalRead = 0; - while (bytesToRead > 0 && EOF != (read = input.read(buffer, 0, bytesToRead))) { - output.write(buffer, 0, read); - totalRead += read; - if (length > 0) { // only adjust length if not reading to the end - // Note the cast must work because buffer.length is an integer - bytesToRead = (int) Math.min(length - totalRead, buffer.length); - } - } - return totalRead; - } - - /** - * Copy chars from a Reader to bytes on an - * OutputStream using the default character encoding of the - * platform, and calling flush. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * Due to the implementation of OutputStreamWriter, this method performs a - * flush. - *

- * This method uses {@link OutputStreamWriter}. - * - * @param input the Reader to read from - * @param output the OutputStream to write to - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void copy(Reader input, OutputStream output) - throws IOException { - copy(input, output, Charset.defaultCharset()); - } - - /** - * Copy chars from a Reader to bytes on an - * OutputStream using the specified character encoding, and - * calling flush. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- *

- * Due to the implementation of OutputStreamWriter, this method performs a - * flush. - *

- *

- * This method uses {@link OutputStreamWriter}. - *

- * - * @param input the Reader to read from - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.3 - */ - public static void copy(Reader input, OutputStream output, Charset encoding) throws IOException { - OutputStreamWriter out = new OutputStreamWriter(output, Charsets.toCharset(encoding)); - copy(input, out); - // XXX Unless anyone is planning on rewriting OutputStreamWriter, - // we have to flush here. - out.flush(); - } - - /** - * Copy chars from a Reader to bytes on an - * OutputStream using the specified character encoding, and - * calling flush. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * Character encoding names can be found at - * IANA. - *

- * Due to the implementation of OutputStreamWriter, this method performs a - * flush. - *

- * This method uses {@link OutputStreamWriter}. - * - * @param input the Reader to read from - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @throws UnsupportedCharsetException thrown instead of {@link UnsupportedEncodingException} in version 2.2 if the encoding is not - * supported. - * @since 1.1 - */ - public static void copy(Reader input, OutputStream output, String encoding) throws IOException { - copy(input, output, Charsets.toCharset(encoding)); - } - - // content equals - //----------------------------------------------------------------------- - - /** - * Compare the contents of two Streams to determine if they are equal or - * not. - *

- * This method buffers the input internally using - * BufferedInputStream if they are not already buffered. - * - * @param input1 the first stream - * @param input2 the second stream - * @return true if the content of the streams are equal or they both don't - * exist, false otherwise - * @throws NullPointerException if either input is null - * @throws IOException if an I/O error occurs - */ - public static boolean contentEquals(InputStream input1, InputStream input2) - throws IOException { - if (!(input1 instanceof BufferedInputStream)) { - input1 = new BufferedInputStream(input1); - } - if (!(input2 instanceof BufferedInputStream)) { - input2 = new BufferedInputStream(input2); - } - - int ch = input1.read(); - while (EOF != ch) { - int ch2 = input2.read(); - if (ch != ch2) { - return false; - } - ch = input1.read(); - } - - int ch2 = input2.read(); - return ch2 == EOF; - } - - /** - * Compare the contents of two Readers to determine if they are equal or - * not. - *

- * This method buffers the input internally using - * BufferedReader if they are not already buffered. - * - * @param input1 the first reader - * @param input2 the second reader - * @return true if the content of the readers are equal or they both don't - * exist, false otherwise - * @throws NullPointerException if either input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static boolean contentEquals(Reader input1, Reader input2) - throws IOException { - - input1 = toBufferedReader(input1); - input2 = toBufferedReader(input2); - - int ch = input1.read(); - while (EOF != ch) { - int ch2 = input2.read(); - if (ch != ch2) { - return false; - } - ch = input1.read(); - } - - int ch2 = input2.read(); - return ch2 == EOF; - } - - /** - * Compare the contents of two Readers to determine if they are equal or - * not, ignoring EOL characters. - *

- * This method buffers the input internally using - * BufferedReader if they are not already buffered. - * - * @param input1 the first reader - * @param input2 the second reader - * @return true if the content of the readers are equal (ignoring EOL differences), false otherwise - * @throws NullPointerException if either input is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static boolean contentEqualsIgnoreEOL(Reader input1, Reader input2) - throws IOException { - BufferedReader br1 = toBufferedReader(input1); - BufferedReader br2 = toBufferedReader(input2); - - String line1 = br1.readLine(); - String line2 = br2.readLine(); - while (line1 != null && line2 != null && line1.equals(line2)) { - line1 = br1.readLine(); - line2 = br2.readLine(); - } - return line1 == null ? line2 == null ? true : false : line1.equals(line2); - } - - /** - * Skip bytes from an input byte stream. - * This implementation guarantees that it will read as many bytes - * as possible before giving up; this may not always be the case for - * subclasses of {@link Reader}. - * - * @param input byte stream to skip - * @param toSkip number of bytes to skip. - * @return number of bytes actually skipped. - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if toSkip is negative - * @see InputStream#skip(long) - * @since 2.0 - */ - public static long skip(InputStream input, long toSkip) throws IOException { - if (toSkip < 0) { - throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip); - } - /* - * N.B. no need to synchronize this because: - we don't care if the buffer is created multiple times (the data - * is ignored) - we always use the same size buffer, so if it it is recreated it will still be OK (if the buffer - * size were variable, we would need to synch. to ensure some other thread did not create a smaller one) - */ - if (SKIP_BYTE_BUFFER == null) { - SKIP_BYTE_BUFFER = new byte[SKIP_BUFFER_SIZE]; - } - long remain = toSkip; - while (remain > 0) { - long n = input.read(SKIP_BYTE_BUFFER, 0, (int) Math.min(remain, SKIP_BUFFER_SIZE)); - if (n < 0) { // EOF - break; - } - remain -= n; - } - return toSkip - remain; - } - - /** - * Skip characters from an input character stream. - * This implementation guarantees that it will read as many characters - * as possible before giving up; this may not always be the case for - * subclasses of {@link Reader}. - * - * @param input character stream to skip - * @param toSkip number of characters to skip. - * @return number of characters actually skipped. - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if toSkip is negative - * @see Reader#skip(long) - * @since 2.0 - */ - public static long skip(Reader input, long toSkip) throws IOException { - if (toSkip < 0) { - throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip); - } - /* - * N.B. no need to synchronize this because: - we don't care if the buffer is created multiple times (the data - * is ignored) - we always use the same size buffer, so if it it is recreated it will still be OK (if the buffer - * size were variable, we would need to synch. to ensure some other thread did not create a smaller one) - */ - if (SKIP_CHAR_BUFFER == null) { - SKIP_CHAR_BUFFER = new char[SKIP_BUFFER_SIZE]; - } - long remain = toSkip; - while (remain > 0) { - long n = input.read(SKIP_CHAR_BUFFER, 0, (int) Math.min(remain, SKIP_BUFFER_SIZE)); - if (n < 0) { // EOF - break; - } - remain -= n; - } - return toSkip - remain; - } - - /** - * Skip the requested number of bytes or fail if there are not enough left. - *

- * This allows for the possibility that {@link InputStream#skip(long)} may - * not skip as many bytes as requested (most likely because of reaching EOF). - * - * @param input stream to skip - * @param toSkip the number of bytes to skip - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if toSkip is negative - * @throws EOFException if the number of bytes skipped was incorrect - * @see InputStream#skip(long) - * @since 2.0 - */ - public static void skipFully(InputStream input, long toSkip) throws IOException { - if (toSkip < 0) { - throw new IllegalArgumentException("Bytes to skip must not be negative: " + toSkip); - } - long skipped = skip(input, toSkip); - if (skipped != toSkip) { - throw new EOFException("Bytes to skip: " + toSkip + " actual: " + skipped); - } - } - - /** - * Skip the requested number of characters or fail if there are not enough left. - *

- * This allows for the possibility that {@link Reader#skip(long)} may - * not skip as many characters as requested (most likely because of reaching EOF). - * - * @param input stream to skip - * @param toSkip the number of characters to skip - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if toSkip is negative - * @throws EOFException if the number of characters skipped was incorrect - * @see Reader#skip(long) - * @since 2.0 - */ - public static void skipFully(Reader input, long toSkip) throws IOException { - long skipped = skip(input, toSkip); - if (skipped != toSkip) { - throw new EOFException("Chars to skip: " + toSkip + " actual: " + skipped); - } - } - - - /** - * Read characters from an input character stream. - * This implementation guarantees that it will read as many characters - * as possible before giving up; this may not always be the case for - * subclasses of {@link Reader}. - * - * @param input where to read input from - * @param buffer destination - * @param offset inital offset into buffer - * @param length length to read, must - * @return actual length read; may be less than requested if EOF was reached - * @throws IOException if a read error occurs - * @since 2.2 - */ - public static int read(Reader input, char[] buffer, int offset, int length) throws IOException { - if (length < 0) { - throw new IllegalArgumentException("Length must not be negative: " + length); - } - int remaining = length; - while (remaining > 0) { - int location = length - remaining; - int count = input.read(buffer, offset + location, remaining); - if (EOF == count) { // EOF - break; - } - remaining -= count; - } - return length - remaining; - } - - /** - * Read characters from an input character stream. - * This implementation guarantees that it will read as many characters - * as possible before giving up; this may not always be the case for - * subclasses of {@link Reader}. - * - * @param input where to read input from - * @param buffer destination - * @return actual length read; may be less than requested if EOF was reached - * @throws IOException if a read error occurs - * @since 2.2 - */ - public static int read(Reader input, char[] buffer) throws IOException { - return read(input, buffer, 0, buffer.length); - } - - /** - * Read bytes from an input stream. - * This implementation guarantees that it will read as many bytes - * as possible before giving up; this may not always be the case for - * subclasses of {@link InputStream}. - * - * @param input where to read input from - * @param buffer destination - * @param offset inital offset into buffer - * @param length length to read, - * @return actual length read; may be less than requested if EOF was reached - * @throws IOException if a read error occurs - * @since 2.2 - */ - public static int read(InputStream input, byte[] buffer, int offset, int length) throws IOException { - if (length < 0) { - throw new IllegalArgumentException("Length must not be negative: " + length); - } - int remaining = length; - while (remaining > 0) { - int location = length - remaining; - int count = input.read(buffer, offset + location, remaining); - if (EOF == count) { // EOF - break; - } - remaining -= count; - } - return length - remaining; - } - - /** - * Read bytes from an input stream. - * This implementation guarantees that it will read as many bytes - * as possible before giving up; this may not always be the case for - * subclasses of {@link InputStream}. - * - * @param input where to read input from - * @param buffer destination - * @return actual length read; may be less than requested if EOF was reached - * @throws IOException if a read error occurs - * @since 2.2 - */ - public static int read(InputStream input, byte[] buffer) throws IOException { - return read(input, buffer, 0, buffer.length); - } - - /** - * Read the requested number of characters or fail if there are not enough left. - *

- * This allows for the possibility that {@link Reader#read(char[], int, int)} may - * not read as many characters as requested (most likely because of reaching EOF). - * - * @param input where to read input from - * @param buffer destination - * @param offset inital offset into buffer - * @param length length to read, must - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if length is negative - * @throws EOFException if the number of characters read was incorrect - * @since 2.2 - */ - public static void readFully(Reader input, char[] buffer, int offset, int length) throws IOException { - int actual = read(input, buffer, offset, length); - if (actual != length) { - throw new EOFException("Length to read: " + length + " actual: " + actual); - } - } - - /** - * Read the requested number of characters or fail if there are not enough left. - *

- * This allows for the possibility that {@link Reader#read(char[], int, int)} may - * not read as many characters as requested (most likely because of reaching EOF). - * - * @param input where to read input from - * @param buffer destination - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if length is negative - * @throws EOFException if the number of characters read was incorrect - * @since 2.2 - */ - public static void readFully(Reader input, char[] buffer) throws IOException { - readFully(input, buffer, 0, buffer.length); - } - - /** - * Read the requested number of bytes or fail if there are not enough left. - *

- * This allows for the possibility that {@link InputStream#read(byte[], int, int)} may - * not read as many bytes as requested (most likely because of reaching EOF). - * - * @param input where to read input from - * @param buffer destination - * @param offset inital offset into buffer - * @param length length to read - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if length is negative - * @throws EOFException if the number of bytes read was incorrect - * @since 2.2 - */ - public static void readFully(InputStream input, byte[] buffer, int offset, int length) throws IOException { - int actual = read(input, buffer, offset, length); - if (actual != length) { - throw new EOFException("Length to read: " + length + " actual: " + actual); - } - } - - /** - * Read the requested number of bytes or fail if there are not enough left. - *

- * This allows for the possibility that {@link InputStream#read(byte[], int, int)} may - * not read as many bytes as requested (most likely because of reaching EOF). - * - * @param input where to read input from - * @param buffer destination - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if length is negative - * @throws EOFException if the number of bytes read was incorrect - * @since 2.2 - */ - public static void readFully(InputStream input, byte[] buffer) throws IOException { - readFully(input, buffer, 0, buffer.length); - } -} diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/LogExceptionHandler.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/LogExceptionHandler.java index 3981a566e..912adbfb7 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/LogExceptionHandler.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/LogExceptionHandler.java @@ -1,9 +1,8 @@ package org.dromara.daxpay.unisdk.common.util; +import lombok.extern.slf4j.Slf4j; import org.dromara.daxpay.unisdk.common.api.PayErrorExceptionHandler; import org.dromara.daxpay.unisdk.common.exception.PayErrorException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; @@ -18,14 +17,14 @@ import org.slf4j.LoggerFactory; * source chanjarster/weixin-java-tools * */ +@Slf4j public class LogExceptionHandler implements PayErrorExceptionHandler { - protected final Logger LOGGER = LoggerFactory.getLogger(PayErrorExceptionHandler.class); @Override public void handle(PayErrorException e) { - LOGGER.error("Error happens", e); + log.error("Error happens", e); } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/MapGen.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/MapGen.java deleted file mode 100644 index 82eaf37c0..000000000 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/MapGen.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.dromara.daxpay.unisdk.common.util; - -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * Map生成工具 - * - * @author Egan - * email egzosn@gmail.com - * date 2021/8/1 - */ -public class MapGen { - - /** - * 属性 - */ - private Map attr; - - public MapGen(K key, V value) { - keyValue(key, value); - } - - public MapGen keyValue(K key, V value) { - if (null == attr){ - attr = new LinkedHashMap<>(); - } - attr.put(key, value); - return this; - } - - - public Map getAttr() { - return attr; - } - - private void setAttr(Map attr) { - this.attr = attr; - } -} diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/MatrixToImageWriter.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/MatrixToImageWriter.java deleted file mode 100644 index 1d214c1ac..000000000 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/MatrixToImageWriter.java +++ /dev/null @@ -1,136 +0,0 @@ -package org.dromara.daxpay.unisdk.common.util; - -import com.google.zxing.BarcodeFormat; -import com.google.zxing.EncodeHintType; -import com.google.zxing.MultiFormatWriter; -import com.google.zxing.common.BitMatrix; - -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.Map; - - -/** - * 二维码生成工具 - * - * @author egan - *

- * email egzosn@gmail.com
- * date  2017/2/7 10:35
- * 
- */ -public class MatrixToImageWriter { - - - private static final int BLACK = 0xFF000000; - private static final int WHITE = 0xFFFFFFFF; - - private MatrixToImageWriter() { - } - - /** - * 根据二维矩阵的碎片 生成对应的二维码图像缓冲 - * - * @param matrix 二维矩阵的碎片 包含 宽高 行,字节 - * @return 二维码图像缓冲 - * @see com.google.zxing.common.BitMatrix - */ - public static BufferedImage toBufferedImage(BitMatrix matrix) { - int width = matrix.getWidth(); - int height = matrix.getHeight(); - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); - } - } - return image; - } - - - /** - * 二维码生成文件 - * - * @param matrix 二维矩阵的碎片 包含 宽高 行,字节 - * @param format 格式 - * @param file 保持的文件地址 - * @throws IOException 文件保存异常 - */ - public static void writeToFile(BitMatrix matrix, String format, File file) - throws IOException { - BufferedImage image = toBufferedImage(matrix); - if (!ImageIO.write(image, format, file)) { - throw new IOException("Could not write an image of format " + format + " to " + file); - } - } - - - /** - * 二维码生成流 - * - * @param matrix 二维矩阵的碎片 包含 宽高 行,字节 - * @param format 格式 - * @param stream 保持的文件输出流 - * @throws IOException 文件保存异常 - */ - public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) - throws IOException { - BufferedImage image = toBufferedImage(matrix); - if (!ImageIO.write(image, format, stream)) { - throw new IOException("Could not write an image of format " + format); - } - } - - - /** - * 二维码信息写成JPG文件 - * - * @param content 二维码信息 - * @param fileUrl 文件地址 - */ - public static void writeInfoToJpgFile(String content, String fileUrl) { - MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); - Map hints = new HashMap(); - hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); - try { - BitMatrix bitMatrix = multiFormatWriter.encode(content, - BarcodeFormat.QR_CODE, 250, 250, hints); - File file1 = new File(fileUrl); - MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1); - } - catch (Exception e) { - e.printStackTrace(); - } - } - - - /** - * 二维码信息写成JPG BufferedImage - * - * @param content 二维码信息 - * @return JPG BufferedImage - */ - public static BufferedImage writeInfoToJpgBuff(String content) { - BufferedImage re = null; - - MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); - Map hints = new HashMap(); - hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); - try { - BitMatrix bitMatrix = multiFormatWriter.encode(content, - BarcodeFormat.QR_CODE, 250, 250, hints); - re = MatrixToImageWriter.toBufferedImage(bitMatrix); - } - catch (Exception e) { - e.printStackTrace(); - } - - return re; - } - - -} diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/Util.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/Util.java index 3eb57498e..1eaf8c512 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/Util.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/Util.java @@ -2,6 +2,7 @@ package org.dromara.daxpay.unisdk.common.util; import java.math.BigDecimal; import java.math.BigInteger; +import java.math.RoundingMode; import java.util.Collection; import java.util.Map; @@ -63,7 +64,7 @@ public class Util { * @return 字节数组 */ public static byte[] byteConvert32Bytes(BigInteger n) { - byte[] tmpd = (byte[]) null; + byte[] tmpd = null; if (n == null) { return null; } @@ -119,28 +120,15 @@ public class Util { * @return 转换后的字符串 */ public static String getHexString(byte[] bytes, boolean upperCase) { - String ret = ""; - for (int i = 0; i < bytes.length; i++) { - ret += Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1); + StringBuilder ret = new StringBuilder(); + for (byte aByte : bytes) { + ret.append(Integer.toString((aByte & 0xff) + 0x100, 16) + .substring(1)); } - return upperCase ? ret.toUpperCase() : ret; + return upperCase ? ret.toString() + .toUpperCase() : ret.toString(); } - /** - * 打印十六进制字符串 - * - * @param bytes 字节数组 - */ - public static void printHexString(byte[] bytes) { - for (int i = 0; i < bytes.length; i++) { - String hex = Integer.toHexString(bytes[i] & 0xFF); - if (hex.length() == 1) { - hex = '0' + hex; - } - System.out.print("0x" + hex.toUpperCase() + ","); - } - System.out.println(""); - } /** * Convert hex string to byte[] @@ -149,7 +137,7 @@ public class Util { * @return byte[] */ public static byte[] hexStringToBytes(String hexString) { - if (hexString == null || "".equals(hexString)) { + if (hexString == null || hexString.isEmpty()) { return null; } @@ -370,13 +358,13 @@ public class Util { public static String hexStringToBinary(String hex) { hex = hex.toUpperCase(); - String result = ""; + StringBuilder result = new StringBuilder(); int max = hex.length(); for (int i = 0; i < max; i++) { char c = hex.charAt(i); - result += Integer.toBinaryString(Character.digit(c, 16)); + result.append(Integer.toBinaryString(Character.digit(c, 16))); } - return result; + return result.toString(); } /** @@ -386,16 +374,16 @@ public class Util { * @return 字符串 */ public static String asciiStringToString(String content) { - String result = ""; + StringBuilder result = new StringBuilder(); int length = content.length() / 2; for (int i = 0; i < length; i++) { String c = content.substring(i * 2, i * 2 + 2); int a = hexStringToAlgorism(c); char b = (char) a; String d = String.valueOf(b); - result += d; + result.append(d); } - return result; + return result.toString(); } /** @@ -422,15 +410,15 @@ public class Util { * @return String */ public static String byteToString(byte[] bytearray) { - String result = ""; + StringBuilder result = new StringBuilder(); char temp; int length = bytearray.length; - for (int i = 0; i < length; i++) { - temp = (char) bytearray[i]; - result += temp; + for (byte b : bytearray) { + temp = (char) b; + result.append(temp); } - return result; + return result.toString(); } /** @@ -478,9 +466,7 @@ public class Util { */ public static String patchHexString(String str, int maxLength) { StringBuilder temp = new StringBuilder(); - for (int i = 0; i < maxLength - str.length(); i++) { - temp.append(0); - } + temp.append("0".repeat(Math.max(0, maxLength - str.length()))); temp.append(str); return temp.toString(); } @@ -556,8 +542,8 @@ public class Util { "Argument b ( byte array ) is null! "); } StringBuilder hs = new StringBuilder(); - for (int n = 0; n < b.length; n++) { - String stmp = Integer.toHexString(b[n] & 0xff); + for (byte value : b) { + String stmp = Integer.toHexString(value & 0xff); if (stmp.length() == 1) { hs.append(0); // hs = hs + "0" + stmp; @@ -571,9 +557,7 @@ public class Util { public static byte[] subByte(byte[] input, int startIndex, int length) { byte[] bt = new byte[length]; - for (int i = 0; i < length; i++) { - bt[i] = input[i + startIndex]; - } + System.arraycopy(input, 0 + startIndex, bt, 0, length); return bt; } @@ -590,7 +574,7 @@ public class Util { * @return 分的金额 */ public static int conversionCentAmount(BigDecimal amount) { - return amount.multiply(HUNDRED).setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); + return amount.multiply(HUNDRED).setScale(0, RoundingMode.HALF_UP).intValue(); } /** @@ -600,7 +584,7 @@ public class Util { * @return 元的金额 两位小数 */ public static BigDecimal conversionAmount(BigDecimal amount) { - return amount.setScale(2, BigDecimal.ROUND_HALF_UP); + return amount.setScale(2, RoundingMode.HALF_UP); } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/XML.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/XML.java index eff2b48f2..ccac9e059 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/XML.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/XML.java @@ -153,8 +153,7 @@ public class XML { if (null == json) { json = new JSONObject(); } - if (json instanceof JSONObject) { - JSONObject j = ((JSONObject) json); + if (json instanceof JSONObject j) { if (j.containsKey(node.getNodeName())) { JSONArray array = new JSONArray(); array.add(json); @@ -299,8 +298,7 @@ public class XML { StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); - String output = writer.getBuffer().toString(); - return output; + return writer.getBuffer().toString(); } catch (TransformerException e) { throw new PayErrorException(new PayException("XML failure", "XML生成失败\n" + e.getMessage())); diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/CertDescriptor.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/CertDescriptor.java index f620b4375..a86af0a32 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/CertDescriptor.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/CertDescriptor.java @@ -14,6 +14,7 @@ */ package org.dromara.daxpay.unisdk.common.util.sign; +import lombok.extern.slf4j.Slf4j; import org.dromara.daxpay.unisdk.common.util.str.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,6 +35,7 @@ import java.util.Enumeration; * date 2016-7-22 下午2:46:20 * 声明:以下代码只是为了方便接入方测试而提供的样例代码,商户可以根据自己需要,按照技术文档编写。该代码仅供参考,不提供编码,性能,规范性等方面的保障 */ +@Slf4j public class CertDescriptor { protected static final Logger LOG = LoggerFactory.getLogger(CertDescriptor.class); /** @@ -66,12 +68,13 @@ public class CertDescriptor { cf = CertificateFactory.getInstance("X.509"); encryptCertTemp = (X509Certificate) cf.generateCertificate(certIn); // 打印证书加载信息,供测试阶段调试 - if (LOG.isWarnEnabled()) { - LOG.warn("[CertId=" + encryptCertTemp.getSerialNumber().toString() + "]"); + if (log.isWarnEnabled()) { + log.warn("[CertId={}]", encryptCertTemp.getSerialNumber() + .toString()); } } catch (CertificateException e) { - LOG.error("InitCert Error", e); + log.error("InitCert Error", e); } finally { if (null != certIn) { @@ -79,7 +82,7 @@ public class CertDescriptor { certIn.close(); } catch (IOException e) { - LOG.error(e.toString()); + log.error(e.toString()); } } } @@ -101,7 +104,7 @@ public class CertDescriptor { encryptCertTemp = initCert(in); } catch (FileNotFoundException e) { - LOG.error("InitCert Error File Not Found", e); + log.error("InitCert Error File Not Found", e); } return encryptCertTemp; } @@ -119,19 +122,10 @@ public class CertDescriptor { if (aliasenum.hasMoreElements()) { keyAlias = aliasenum.nextElement(); } - PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, pwd.toCharArray()); - return privateKey; + return (PrivateKey) keyStore.getKey(keyAlias, pwd.toCharArray()); } - catch (KeyStoreException e) { - LOG.error("getSignCertPrivateKey Error", e); - return null; - } - catch (UnrecoverableKeyException e) { - LOG.error("getSignCertPrivateKey Error", e); - return null; - } - catch (NoSuchAlgorithmException e) { - LOG.error("getSignCertPrivateKey Error", e); + catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) { + log.error("getSignCertPrivateKey Error", e); return null; } } @@ -153,7 +147,7 @@ public class CertDescriptor { return cert.getSerialNumber().toString(); } catch (Exception e) { - LOG.error("getSignCertId Error", e); + log.error("getSignCertId Error", e); return null; } } @@ -172,12 +166,12 @@ public class CertDescriptor { } try { keyStore = getKeyInfo(signCertPath, signCertPwd, signCertType); - if (LOG.isInfoEnabled()) { - LOG.info("InitSignCert Successful. CertId=[" + getSignCertId() + "]"); + if (log.isInfoEnabled()) { + log.info("InitSignCert Successful. CertId=[{}]", getSignCertId()); } } catch (IOException e) { - LOG.error("InitSignCert Error", e); + log.error("InitSignCert Error", e); } } @@ -194,8 +188,8 @@ public class CertDescriptor { keyStore = null; } keyStore = getKeyInfo(signCert, signCertPwd, signCertType); - if (LOG.isInfoEnabled()) { - LOG.info("InitSignCert Successful. CertId=[" + getSignCertId() + "]"); + if (log.isInfoEnabled()) { + log.info("InitSignCert Successful. CertId=[{}]", getSignCertId()); } } @@ -209,8 +203,8 @@ public class CertDescriptor { * @throws IOException */ private KeyStore getKeyInfo(String fxKeyFile, String keyPwd, String type) throws IOException { - if (LOG.isWarnEnabled()) { - LOG.warn("加载签名证书==>" + fxKeyFile); + if (log.isWarnEnabled()) { + log.warn("加载签名证书==>{}", fxKeyFile); } FileInputStream fis = new FileInputStream(fxKeyFile); return getKeyInfo(fis, keyPwd, type); @@ -229,19 +223,18 @@ public class CertDescriptor { try { KeyStore ks = KeyStore.getInstance(type); - if (LOG.isWarnEnabled()) { - LOG.warn("Load RSA CertPath,Pwd=[" + keyPwd + "],type=[" + type + "]"); + if (log.isWarnEnabled()) { + log.warn("Load RSA CertPath,Pwd=[{}],type=[{}]", keyPwd, type); } char[] nPassword = null; - nPassword = null == keyPwd || "".equals(keyPwd.trim()) ? null : keyPwd.toCharArray(); - if (null != ks) { - ks.load(fxKeyFile, nPassword); - } + nPassword = null == keyPwd || keyPwd.trim() + .isEmpty() ? null : keyPwd.toCharArray(); + ks.load(fxKeyFile, nPassword); return ks; } catch (Exception e) { - LOG.error("getKeyInfo Error", e); + log.error("getKeyInfo Error", e); return null; } finally { @@ -250,7 +243,7 @@ public class CertDescriptor { fxKeyFile.close(); } catch (IOException e) { - LOG.error("getKeyInfo Error", e); + log.error("getKeyInfo Error", e); } } } @@ -276,7 +269,7 @@ public class CertDescriptor { return cert.getSerialNumber().toString(); } catch (KeyStoreException e) { - LOG.error("getCertIdIdByStore Error", e); + log.error("getCertIdIdByStore Error", e); return null; } } @@ -290,12 +283,12 @@ public class CertDescriptor { public void initPublicCert(String certPath) { if (!StringUtils.isEmpty(certPath)) { publicKeyCert = initCert(certPath); - if (LOG.isInfoEnabled()) { - LOG.info("Load PublicKeyCert Successful"); + if (log.isInfoEnabled()) { + log.info("Load PublicKeyCert Successful"); } } - else if (LOG.isInfoEnabled()) { - LOG.info("PublicKeyCert is empty"); + else if (log.isInfoEnabled()) { + log.info("PublicKeyCert is empty"); } } @@ -307,12 +300,12 @@ public class CertDescriptor { public void initPublicCert(InputStream cert) { if (null != cert) { publicKeyCert = initCert(cert); - if (LOG.isInfoEnabled()) { - LOG.info("Load PublicKeyCert Successful"); + if (log.isInfoEnabled()) { + log.info("Load PublicKeyCert Successful"); } } - else if (LOG.isInfoEnabled()) { - LOG.info("PublicKeyCert is empty"); + else if (log.isInfoEnabled()) { + log.info("PublicKeyCert is empty"); } } @@ -327,12 +320,12 @@ public class CertDescriptor { initRootCert(new FileInputStream(certPath)); } catch (FileNotFoundException e) { - LOG.info("RootCert is empty"); + log.info("RootCert is empty"); } } - else if (LOG.isInfoEnabled()) { - LOG.info("RootCert is empty"); + else if (log.isInfoEnabled()) { + log.info("RootCert is empty"); } } @@ -344,12 +337,12 @@ public class CertDescriptor { public void initRootCert(InputStream cert) { if (null != cert) { rootKeyCert = initCert(cert); - if (LOG.isInfoEnabled()) { - LOG.info("Load RootCert Successful"); + if (log.isInfoEnabled()) { + log.info("Load RootCert Successful"); } } - else if (LOG.isInfoEnabled()) { - LOG.info("RootCert is empty"); + else if (log.isInfoEnabled()) { + log.info("RootCert is empty"); } } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/SignTextUtils.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/SignTextUtils.java index ef44949d6..924bf774e 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/SignTextUtils.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/SignTextUtils.java @@ -69,7 +69,7 @@ public final class SignTextUtils { if (null != ignoreKey) { Arrays.sort(ignoreKey); } - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); // TODO 2016/11/11 10:14 author: egan 已经排序好处理 if (parameters instanceof SortedMap) { for (Map.Entry entry : parameters.entrySet()) { @@ -78,7 +78,7 @@ public final class SignTextUtils { continue; } String valStr = v.toString().trim(); - if ("".equals(valStr) || (null != ignoreKey && Arrays.binarySearch(ignoreKey, entry.getKey()) >= 0)) { + if (valStr.isEmpty() || (null != ignoreKey && Arrays.binarySearch(ignoreKey, entry.getKey()) >= 0)) { continue; } sb.append(entry.getKey()).append("=").append(valStr).append(separator); @@ -96,32 +96,31 @@ public final class SignTextUtils { private static String sortMapParameterText(Map parameters, String separator, boolean ignoreNullValue, String... ignoreKey) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); // TODO 2016/11/11 10:14 author: egan 未排序须处理 List keys = new ArrayList(parameters.keySet()); //排序 Collections.sort(keys); for (String k : keys) { - String valueStr = ""; + StringBuilder valueStr = new StringBuilder(); Object o = parameters.get(k); if (ignoreNullValue && null == o) { continue; } - if (o instanceof String[]) { - String[] values = (String[]) o; + if (o instanceof String[] values) { for (int i = 0; i < values.length; i++) { String value = values[i].trim(); - if ("".equals(value)) { + if (value.isEmpty()) { continue; } - valueStr += (i == values.length - 1) ? value : value + ","; + valueStr.append((i == values.length - 1) ? value : value + ","); } } else { - valueStr = o.toString(); + valueStr = new StringBuilder(o.toString()); } - if (StringUtils.isBlank(valueStr) || (null != ignoreKey && Arrays.binarySearch(ignoreKey, k) >= 0)) { + if (StringUtils.isBlank(valueStr.toString()) || (null != ignoreKey && Arrays.binarySearch(ignoreKey, k) >= 0)) { continue; } sb.append(k).append("=").append(valueStr).append(separator); @@ -141,7 +140,7 @@ public final class SignTextUtils { * @return 参数排序好的值 */ public static String parameters2Md5Str(Object parameters, String separator) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); if (parameters instanceof LinkedHashMap) { Set keys = (Set) ((LinkedHashMap) parameters).keySet(); diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/SignUtils.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/SignUtils.java index 3d9831da3..3c1790a6f 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/SignUtils.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/SignUtils.java @@ -3,9 +3,7 @@ package org.dromara.daxpay.unisdk.common.util.sign; import org.dromara.daxpay.unisdk.common.bean.SignType; import org.dromara.daxpay.unisdk.common.util.sign.encrypt.HmacSha256; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import java.security.Security; import java.util.Map; import static org.dromara.daxpay.unisdk.common.util.sign.SignTextUtils.parameterText; @@ -192,19 +190,4 @@ public enum SignUtils implements SignType { return this.verify(parameterText(params), sign, key, characterEncoding); } - /** - * 初始化BC - */ - public static void initBc() { - String javaVersion = System.getProperty("java.version"); - if (javaVersion.contains("1.8") || javaVersion.startsWith("8")) { - if (null == Security.getProvider("BC")) { - Security.removeProvider("SunEC"); - Security.addProvider(new BouncyCastleProvider()); - } - } - - } - - } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/AES.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/AES.java deleted file mode 100644 index 4778f981e..000000000 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/AES.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.dromara.daxpay.unisdk.common.util.sign.encrypt; - -import org.dromara.daxpay.unisdk.common.util.sign.SignUtils; -import org.apache.commons.codec.digest.DigestUtils; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; -import java.io.IOException; -import java.security.GeneralSecurityException; - -/** - * AES 加解密 - * - * @author Egan - *
- *  email egan@egzosn.com
- *  date 2022/3/20
- *  
- */ -public class AES { - /** - * 密钥算法 - */ - private static final String ALGORITHM = "AES"; - /** - * 加解密算法/工作模式/填充方式 - */ - private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS7Padding"; - - static { - SignUtils.initBc(); - } - - - /** - * 解密 - * - * @param content 密文 - * @param privateKey 商户私钥 - * @param characterEncoding 编码格式 - * @return 解密后的字符串 - * @throws GeneralSecurityException 解密异常 - * @throws IOException IOException - */ - public static String decrypt(String content, String privateKey, String characterEncoding) throws GeneralSecurityException, IOException { - byte[] reqInfoB = Base64.decode(content); - String key$ = DigestUtils.md5Hex(privateKey).toLowerCase(); - Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING, "BC"); - SecretKeySpec secretKeySpec = new SecretKeySpec(key$.getBytes(), ALGORITHM); - cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); - return new String(cipher.doFinal(reqInfoB), characterEncoding); - } - - /** - * 解密 - * - * @param content 密文 - * @param privateKey 商户私钥 - * @param characterEncoding 编码格式 - * @return 解密后的字符串 - * @throws GeneralSecurityException 解密异常 - * @throws IOException IOException - */ - public static String encrypt(String content, String privateKey, String characterEncoding) throws GeneralSecurityException, IOException { - String key$ = DigestUtils.md5Hex(privateKey).toLowerCase(); - Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING, "BC"); - SecretKeySpec secretKeySpec = new SecretKeySpec(key$.getBytes(), ALGORITHM); - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); - byte[] doFinal = cipher.doFinal(content.getBytes(characterEncoding)); - return Base64.encode(doFinal); - } - -} diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/HmacSha256.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/HmacSha256.java index 2051070a6..cdd422664 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/HmacSha256.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/HmacSha256.java @@ -1,9 +1,8 @@ package org.dromara.daxpay.unisdk.common.util.sign.encrypt; +import lombok.extern.slf4j.Slf4j; import org.dromara.daxpay.unisdk.common.bean.result.PayException; import org.dromara.daxpay.unisdk.common.exception.PayErrorException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; @@ -17,8 +16,8 @@ import java.security.GeneralSecurityException; * email egzosn@gmail.com * date 2021/8/1 */ +@Slf4j public class HmacSha256 { - private static final Logger LOG = LoggerFactory.getLogger(HmacSha256.class); /** * 签名 @@ -38,15 +37,12 @@ public class HmacSha256 { byte[] array = sha256HMAC.doFinal(content.getBytes(characterEncoding)); StringBuilder sb = new StringBuilder(); for (byte item : array) { - sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3)); + sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3); } return sb.toString().toUpperCase(); } - catch (UnsupportedEncodingException e) { - LOG.error("", e); - } - catch (GeneralSecurityException e) { - LOG.error("", e); + catch (UnsupportedEncodingException | GeneralSecurityException e) { + log.error("", e); } throw new PayErrorException(new PayException("fail", "HMACSHA256 签名异常")); diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/RSA.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/RSA.java index ba3cbad68..d43b0a4d9 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/RSA.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/RSA.java @@ -1,6 +1,7 @@ package org.dromara.daxpay.unisdk.common.util.sign.encrypt; +import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,6 +23,7 @@ import java.security.spec.X509EncodedKeySpec; * email egzosn@gmail.com * */ +@Slf4j public class RSA { private static final Logger LOG = LoggerFactory.getLogger(RSA.class); private static final String ALGORITHM = "RSA"; @@ -54,11 +56,8 @@ public class RSA { return Base64.encode(signed); } - catch (GeneralSecurityException e) { - LOG.error("", e); - } - catch (UnsupportedEncodingException e) { - LOG.error("", e); + catch (GeneralSecurityException | UnsupportedEncodingException e) { + log.error("", e); } return null; @@ -82,11 +81,8 @@ public class RSA { byte[] signed = signature.sign(); return Base64.encode(signed); } - catch (GeneralSecurityException e) { - LOG.error("", e); - } - catch (UnsupportedEncodingException e) { - LOG.error("", e); + catch (GeneralSecurityException | UnsupportedEncodingException e) { + log.error("", e); } return null; @@ -132,11 +128,8 @@ public class RSA { PublicKey pubKey = getPublicKey(publicKey, ALGORITHM); return verify(content, sign, pubKey, signAlgorithms, characterEncoding); } - catch (GeneralSecurityException e) { - LOG.error("", e); - } - catch (IOException e) { - LOG.error("", e); + catch (GeneralSecurityException | IOException e) { + log.error("", e); } return false; } @@ -158,11 +151,8 @@ public class RSA { signature.update(content.getBytes(characterEncoding)); return signature.verify(Base64.decode(sign)); } - catch (GeneralSecurityException e) { - LOG.error("", e); - } - catch (IOException e) { - LOG.error("", e); + catch (GeneralSecurityException | IOException e) { + log.error("", e); } return false; } @@ -238,14 +228,12 @@ public class RSA { else { block = new byte[bufl]; - for (int i = 0; i < bufl; i++) { - block[i] = buf[i]; - } + System.arraycopy(buf, 0, block, 0, bufl); } writer.write(cipher.doFinal(block)); } - return new String(writer.toByteArray(), characterEncoding); + return writer.toString(characterEncoding); } } @@ -263,8 +251,7 @@ public class RSA { keyBytes = Base64.decode(key); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); - PrivateKey privateKey = keyFactory.generatePrivate(keySpec); - return privateKey; + return keyFactory.generatePrivate(keySpec); } /** @@ -309,8 +296,7 @@ public class RSA { } X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decode(sb.toString())); KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm); - PublicKey publicKey = keyFactory.generatePublic(pubX509); - return publicKey; + return keyFactory.generatePublic(pubX509); } } diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/sm3/SM3.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/sm3/SM3.java index 84b43fcfc..860751426 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/sm3/SM3.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/sign/encrypt/sm3/SM3.java @@ -109,9 +109,7 @@ public class SM3 { private static int[][] expand(int[] B) { int[] W = new int[68]; int[] W1 = new int[64]; - for (int i = 0; i < B.length; i++) { - W[i] = B[i]; - } + System.arraycopy(B, 0, W, 0, B.length); for (int i = 16; i < 68; i++) { W[i] = P1(W[i - 16] ^ W[i - 9] ^ bitCycleLeft(W[i - 3], 15)) @@ -122,8 +120,7 @@ public class SM3 { W1[i] = W[i] ^ W[i + 4]; } - int[][] arr = new int[][]{W, W1}; - return arr; + return new int[][]{W, W1}; } private static byte[] bigEndianIntToByte(int num) { @@ -154,23 +151,19 @@ public class SM3 { // 逻辑位运算函数 private static int FF1j(int X, int Y, int Z) { - int tmp = X ^ Y ^ Z; - return tmp; + return X ^ Y ^ Z; } private static int FF2j(int X, int Y, int Z) { - int tmp = ((X & Y) | (X & Z) | (Y & Z)); - return tmp; + return ((X & Y) | (X & Z) | (Y & Z)); } private static int GG1j(int X, int Y, int Z) { - int tmp = X ^ Y ^ Z; - return tmp; + return X ^ Y ^ Z; } private static int GG2j(int X, int Y, int Z) { - int tmp = (X & Y) | (~X & Z); - return tmp; + return (X & Y) | (~X & Z); } private static int P0(int X) { @@ -178,13 +171,11 @@ public class SM3 { y = bitCycleLeft(X, 9); int z = rotateLeft(X, 17); z = bitCycleLeft(X, 17); - int t = X ^ y ^ z; - return t; + return X ^ y ^ z; } private static int P1(int X) { - int t = X ^ bitCycleLeft(X, 15) ^ bitCycleLeft(X, 23); - return t; + return X ^ bitCycleLeft(X, 15) ^ bitCycleLeft(X, 23); } /** diff --git a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/str/StringUtils.java b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/str/StringUtils.java index c4b3a2dbe..49b5dd374 100644 --- a/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/str/StringUtils.java +++ b/daxpay-single/daxpay-single-unisdk/src/main/java/org/dromara/daxpay/unisdk/common/util/str/StringUtils.java @@ -1,5 +1,7 @@ package org.dromara.daxpay.unisdk.common.util.str; +import cn.hutool.core.util.StrUtil; + import java.io.UnsupportedEncodingException; import java.util.UUID; @@ -64,7 +66,7 @@ public class StringUtils { * @return {@code true} if the CharSequence is not empty and not null */ public static boolean isNotEmpty(CharSequence cs) { - return !StringUtils.isEmpty(cs); + return !StrUtil.isEmpty(cs); } /** @@ -88,7 +90,7 @@ public class StringUtils { return true; } for (int i = 0; i < strLen; i++) { - if (Character.isWhitespace(cs.charAt(i)) == false) { + if (!Character.isWhitespace(cs.charAt(i))) { return false; } }