style 统一SDK代码优化

This commit is contained in:
DaxPay
2024-10-09 13:41:04 +08:00
parent 6ccd0a0d3b
commit b2cda61f02
59 changed files with 282 additions and 1367 deletions

View File

@@ -17,7 +17,7 @@ import java.math.BigDecimal;
public class MchAppLocal {
/** 应用号 */
private String appId;;
private String appId;
/** 签名方式 */
private String signType;

View File

@@ -74,7 +74,7 @@ public class MerchantCallbackSendService {
if (StrUtil.equalsIgnoreCase(body, "SUCCESS")){
task.setSendCount(task.getSendCount() + 1)
.setLatestTime(sendTime)
.setSuccess(true);;
.setSuccess(true);
record.setSuccess(true);
// 如果为自动发送且延迟次数, 延迟次数也+1
if (autoSend && Objects.nonNull(task.getDelayCount())){

View File

@@ -373,35 +373,31 @@ public class ReconcileStatementService {
.setChannelTradeTime(LocalDateTimeUtil.format(discrepancyTrade.getChannelTradeTime(), DatePattern.CHINESE_DATE_TIME_PATTERN))
);
// 处理远程短单
case REMOTE_NOT_EXISTS -> {
tradeExcels.add(new ReconcileTradeExcel()
.setResult(ReconcileDiscrepancyTypeEnum.REMOTE_NOT_EXISTS.getName())
.setTradeNo(discrepancyTrade.getTradeNo())
.setBizTradeNo(discrepancyTrade.getBizTradeNo())
.setOutTradeNo(discrepancyTrade.getOutTradeNo())
.setTradeType(TradeTypeEnum.findByCode(discrepancyTrade.getTradeType()).getName())
.setTradeAmount(discrepancyTrade.getTradeAmount().toString())
.setTradeStatus(discrepancyTrade.getTradeStatus())
.setTradeTime(LocalDateTimeUtil.format(discrepancyTrade.getTradeTime(), DatePattern.CHINESE_DATE_TIME_PATTERN))
);
}
case REMOTE_NOT_EXISTS -> tradeExcels.add(new ReconcileTradeExcel()
.setResult(ReconcileDiscrepancyTypeEnum.REMOTE_NOT_EXISTS.getName())
.setTradeNo(discrepancyTrade.getTradeNo())
.setBizTradeNo(discrepancyTrade.getBizTradeNo())
.setOutTradeNo(discrepancyTrade.getOutTradeNo())
.setTradeType(TradeTypeEnum.findByCode(discrepancyTrade.getTradeType()).getName())
.setTradeAmount(discrepancyTrade.getTradeAmount().toString())
.setTradeStatus(discrepancyTrade.getTradeStatus())
.setTradeTime(LocalDateTimeUtil.format(discrepancyTrade.getTradeTime(), DatePattern.CHINESE_DATE_TIME_PATTERN))
);
// 处理信息不一致订单
case NOT_MATCH -> {
tradeExcels.add(new ReconcileTradeExcel()
.setResult(ReconcileDiscrepancyTypeEnum.NOT_MATCH.getName())
.setTradeNo(discrepancyTrade.getTradeNo())
.setBizTradeNo(discrepancyTrade.getBizTradeNo())
.setOutTradeNo(discrepancyTrade.getOutTradeNo())
.setTradeType(TradeTypeEnum.findByCode(discrepancyTrade.getTradeType()).getName())
.setTradeAmount(discrepancyTrade.getTradeAmount().toString())
.setTradeStatus(discrepancyTrade.getTradeStatus())
.setTradeTime(LocalDateTimeUtil.format(discrepancyTrade.getTradeTime(), DatePattern.CHINESE_DATE_TIME_PATTERN))
.setChannelTradeNo(discrepancy.getChannelTradeNo())
.setChannelTradeAmount(discrepancy.getChannelTradeAmount().toString())
.setChannelTradeStatus(discrepancy.getChannelTradeStatus())
.setChannelTradeTime(LocalDateTimeUtil.format(discrepancy.getChannelTradeTime(), DatePattern.CHINESE_DATE_TIME_PATTERN))
);
}
case NOT_MATCH -> tradeExcels.add(new ReconcileTradeExcel()
.setResult(ReconcileDiscrepancyTypeEnum.NOT_MATCH.getName())
.setTradeNo(discrepancyTrade.getTradeNo())
.setBizTradeNo(discrepancyTrade.getBizTradeNo())
.setOutTradeNo(discrepancyTrade.getOutTradeNo())
.setTradeType(TradeTypeEnum.findByCode(discrepancyTrade.getTradeType()).getName())
.setTradeAmount(discrepancyTrade.getTradeAmount().toString())
.setTradeStatus(discrepancyTrade.getTradeStatus())
.setTradeTime(LocalDateTimeUtil.format(discrepancyTrade.getTradeTime(), DatePattern.CHINESE_DATE_TIME_PATTERN))
.setChannelTradeNo(discrepancy.getChannelTradeNo())
.setChannelTradeAmount(discrepancy.getChannelTradeAmount().toString())
.setChannelTradeStatus(discrepancy.getChannelTradeStatus())
.setChannelTradeTime(LocalDateTimeUtil.format(discrepancy.getChannelTradeTime(), DatePattern.CHINESE_DATE_TIME_PATTERN))
);
}
}
return tradeExcels;

View File

@@ -10,21 +10,20 @@
</parent>
<artifactId>daxpay-single-unisdk</artifactId>
<description>统一支付SDK基础包</description>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<httpmime.version>4.5.4</httpmime.version>
<httpmime.version>4.5.14</httpmime.version>
<fastjson.version>1.2.83_noneautotype</fastjson.version>
</properties>
<dependencies>
<!-- 支付核心包 -->
<dependency>
<groupId>cn.bootx.platform</groupId>
<artifactId>bootx-platform-core</artifactId>
<version>${bootx-platform.version}</version>
<groupId>org.dromara.daxpay</groupId>
<artifactId>daxpay-single-core</artifactId>
<version>${daxpay.version}</version>
</dependency>
<!--httpcomponents-->
<dependency>
@@ -32,18 +31,13 @@
<artifactId>httpmime</artifactId>
<version>${httpmime.version}</version>
</dependency>
<!--json-->
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- log4j 日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -1,5 +1,7 @@
package org.dromara.daxpay.unisdk.common.api;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
@@ -7,11 +9,10 @@ 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.sign.SignUtils;
import org.dromara.daxpay.unisdk.common.util.str.StringUtils;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
@@ -24,13 +25,10 @@ import java.util.*;
* </pre>
*/
@Slf4j
public abstract class BasePayService<PC extends PayConfigStorage> implements PayService<PC> {
public abstract class BasePayService<PC extends PayConfigStorage> implements UniPayService<PC> {
protected PC payConfigStorage;
protected HttpRequestTemplate requestTemplate;
protected int retrySleepMillis = 1000;
protected int maxRetryTimes = 5;
/**
* 支付消息处理器
*/
@@ -38,7 +36,7 @@ public abstract class BasePayService<PC extends PayConfigStorage> implements Pay
/**
* 支付消息拦截器
*/
protected List<PayMessageInterceptor<PayMessage, PayService>> interceptors = new ArrayList<>();
protected List<PayMessageInterceptor<PayMessage, UniPayService>> interceptors = new ArrayList<>();
private Charset inputCharset = Consts.UTF_8;
@@ -51,7 +49,7 @@ public abstract class BasePayService<PC extends PayConfigStorage> implements Pay
public BasePayService setPayConfigStorage(PC payConfigStorage) {
this.payConfigStorage = payConfigStorage;
if (StringUtils.isNotEmpty(payConfigStorage.getInputCharset())) {
if (StrUtil.isNotEmpty(payConfigStorage.getInputCharset())) {
this.inputCharset = Charset.forName(payConfigStorage.getInputCharset());
}
return this;
@@ -100,12 +98,7 @@ public abstract class BasePayService<PC extends PayConfigStorage> implements Pay
*/
protected String authorizationString(String user, String password) {
String base64ClientID = null;
try {
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);
}
base64ClientID = Base64.encode(String.format("%s:%s", user, password).getBytes(StandardCharsets.UTF_8));
return base64ClientID;
}
@@ -142,11 +135,11 @@ public abstract class BasePayService<PC extends PayConfigStorage> implements Pay
* @return 对应页面重定向信息
*/
@Override
public <O extends PayOrder> String toPay(O order) {
if (StringUtils.isNotEmpty(order.getSubject()) && order.getSubject().contains("'")) {
public <O extends UniOrder> String toPay(O order) {
if (StrUtil.isNotEmpty(order.getSubject()) && order.getSubject().contains("'")) {
order.setSubject(order.getSubject().replace("'", ""));
}
if (StringUtils.isNotEmpty(order.getBody()) && order.getBody().contains("'")) {
if (StrUtil.isNotEmpty(order.getBody()) && order.getBody().contains("'")) {
order.setBody(order.getBody().replace("'", ""));
}
Map<String, Object> orderInfo = orderInfo(order);
@@ -161,7 +154,7 @@ public abstract class BasePayService<PC extends PayConfigStorage> implements Pay
* @return 对应app所需参数信息
*/
@Override
public <O extends PayOrder> Map<String, Object> app(O order) {
public <O extends UniOrder> Map<String, Object> app(O order) {
return orderInfo(order);
}
@@ -173,7 +166,7 @@ public abstract class BasePayService<PC extends PayConfigStorage> implements Pay
* @return 返回支付结果
*/
@Override
public <O extends PayOrder> Map<String, Object> jsApi(O order) {
public <O extends UniOrder> Map<String, Object> jsApi(O order) {
return Collections.emptyMap();
}
@@ -196,7 +189,7 @@ public abstract class BasePayService<PC extends PayConfigStorage> implements Pay
sb.append(values[i]).append((i == len - 1) ? "" : ',');
}
String valueStr = sb.toString();
if (StringUtils.isNotEmpty(payConfigStorage.getInputCharset()) && !valueStr.matches("\\w+")) {
if (StrUtil.isNotEmpty(payConfigStorage.getInputCharset()) && !valueStr.matches("\\w+")) {
if (valueStr.equals(new String(valueStr.getBytes(Consts.ISO_8859_1), Consts.ISO_8859_1))) {
valueStr = new String(valueStr.getBytes(Consts.ISO_8859_1), inputCharset);
}
@@ -238,7 +231,7 @@ public abstract class BasePayService<PC extends PayConfigStorage> implements Pay
* @return 对应的转账结果
*/
@Override
public Map<String, Object> transfer(TransferOrder order) {
public Map<String, Object> transfer(UniTransferOrder order) {
return Collections.emptyMap();
}
@@ -246,7 +239,7 @@ public abstract class BasePayService<PC extends PayConfigStorage> implements Pay
* 设置支付消息处理器,这里用于处理具体的支付业务
*
* @param handler 消息处理器
* 配合{@link PayService#payBack(Map, InputStream)}进行使用
* 配合{@link UniPayService#payBack(Map, InputStream)}进行使用
* <p>
* 默认使用{@link DefaultPayMessageHandler }进行实现
*/
@@ -257,7 +250,7 @@ public abstract class BasePayService<PC extends PayConfigStorage> implements Pay
/**
* 获取支付消息处理器,这里用于处理具体的支付业务
* 配合{@link PayService#payBack(Map, InputStream)}进行使用
* 配合{@link UniPayService#payBack(Map, InputStream)}进行使用
* <p>
*
* @return 默认使用{@link DefaultPayMessageHandler }进行实现
@@ -273,7 +266,7 @@ public abstract class BasePayService<PC extends PayConfigStorage> implements Pay
* 设置支付消息拦截器
*
* @param interceptor 消息拦截器
* 配合{@link PayService#payBack(Map, InputStream)}进行使用, 做一些预前处理
* 配合{@link UniPayService#payBack(Map, InputStream)}进行使用, 做一些预前处理
*/
@Override
public void addPayMessageInterceptor(PayMessageInterceptor interceptor) {

View File

@@ -1,38 +0,0 @@
/*
* Copyright 2017 the original egan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.daxpay.unisdk.common.api;
import java.util.Map;
/**
* 回调,可用于类型转换
* @author egan
* <pre>
* email egzosn@gmail.com
* date 2017/3/7 18:55
* </pre>
*/
public interface Callback<T> {
/**
* 执行者
* @param map 需要转化的map
* @return 处理过后的类型对象
*/
T perform(Map<String, Object> map);
}

View File

@@ -21,7 +21,7 @@ import java.util.Map;
* </pre>
*/
@Slf4j
public class DefaultPayMessageHandler implements PayMessageHandler<PayMessage, PayService> {
public class DefaultPayMessageHandler implements PayMessageHandler<PayMessage, UniPayService> {
protected final Logger LOG = LoggerFactory.getLogger(DefaultPayMessageHandler.class);
/**
@@ -31,9 +31,9 @@ public class DefaultPayMessageHandler implements PayMessageHandler<PayMessage, P
* @return xml, text格式的消息如果在异步规则里处理的话可以返回null
*/
@Override
public PayOutMessage handle(PayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
public PayOutMessage handle(PayMessage payMessage, Map<String, Object> context, UniPayService payService) throws PayErrorException {
if (log.isInfoEnabled()) {
log.info("回调支付消息处理器,回调消息:" + JSON.toJSONString(payMessage));
log.info("回调支付消息处理器,回调消息:{}", JSON.toJSONString(payMessage));
}
return payService.successPayOutMessage(payMessage);
}

View File

@@ -19,7 +19,7 @@ import java.util.Map;
* source Daniel Qian
* </pre>
*/
public interface PayMessageHandler<M extends PayMessage, S extends PayService> {
public interface PayMessageHandler<M extends PayMessage, S extends UniPayService> {
/**
* 处理支付回调消息的处理器接口

View File

@@ -18,7 +18,7 @@ import java.util.Map;
* source Daniel Qian
* </pre>
*/
public interface PayMessageInterceptor<M extends PayMessage, S extends PayService> {
public interface PayMessageInterceptor<M extends PayMessage, S extends UniPayService> {
/**
* 拦截微信消息

View File

@@ -52,11 +52,11 @@ public class PayMessageRouter {
/**
* 规则集
*/
private final List<PayMessageRouterRule> rules = new ArrayList<PayMessageRouterRule>();
private final List<PayMessageRouterRule> rules = new ArrayList<>();
/**
* 支付服务
*/
private final PayService payService;
private final UniPayService payService;
/**
* 异步线程处理器
* -- SETTER --
@@ -89,7 +89,7 @@ public class PayMessageRouter {
*
* @param payService 支付服务
*/
public PayMessageRouter(PayService payService) {
public PayMessageRouter(UniPayService payService) {
this.payService = payService;
this.executorService = Executors.newFixedThreadPool(DEFAULT_THREAD_POOL_SIZE);
this.exceptionHandler = new LogExceptionHandler();
@@ -136,7 +136,7 @@ public class PayMessageRouter {
*/
public PayOutMessage route(final PayMessage payMessage) {
final List<PayMessageRouterRule> matchRules = new ArrayList<PayMessageRouterRule>();
final List<PayMessageRouterRule> matchRules = new ArrayList<>();
// 收集匹配的规则
for (final PayMessageRouterRule rule : rules) {
if (rule.test(payMessage)) {
@@ -152,7 +152,7 @@ public class PayMessageRouter {
}
PayOutMessage res = null;
final List<Future> futures = new ArrayList<Future>();
final List<Future> futures = new ArrayList<>();
for (final PayMessageRouterRule rule : matchRules) {
// 返回最后一个非异步的rule的执行结果
if (rule.isAsync()) {
@@ -166,7 +166,7 @@ public class PayMessageRouter {
res = rule.service(payMessage, payService, exceptionHandler);
// 在同步操作结束session访问结束
if (log.isDebugEnabled()) {
log.debug("End session access: async=false, fromPay=" + payMessage.getFromPay());
log.debug("End session access: async=false, fromPay={}", payMessage.getFromPay());
}
}
}
@@ -176,13 +176,10 @@ public class PayMessageRouter {
for (Future future : futures) {
try {
future.get();
log.debug("End session access: async=true, fromPay=" + payMessage.getFromPay());
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) {
catch (InterruptedException | ExecutionException e) {
log.error("Error happened when wait task finish", e);
}
}

View File

@@ -69,10 +69,10 @@ public class PayMessageRouterRule {
private boolean reEnter = false;
@Setter
private List<PayMessageHandler> handlers = new ArrayList<PayMessageHandler>();
private List<PayMessageHandler> handlers = new ArrayList<>();
@Setter
private List<PayMessageInterceptor> interceptors = new ArrayList<PayMessageInterceptor>();
private List<PayMessageInterceptor> interceptors = new ArrayList<>();
public PayMessageRouterRule(PayMessageRouter routerBuilder) {
this.routerBuilder = routerBuilder;
@@ -274,12 +274,12 @@ public class PayMessageRouterRule {
* @return 支付响应消息
*/
protected PayOutMessage service(PayMessage payMessage,
PayService payService,
UniPayService payService,
PayErrorExceptionHandler exceptionHandler) {
try {
Map<String, Object> context = new HashMap<String, Object>();
Map<String, Object> context = new HashMap<>();
// 如果拦截器不通过
for (PayMessageInterceptor interceptor : this.interceptors) {
if (!interceptor.intercept(payMessage, context, payService)) {

View File

@@ -1,7 +1,7 @@
package org.dromara.daxpay.unisdk.common.api;
import org.dromara.daxpay.unisdk.common.bean.AssistOrder;
import org.dromara.daxpay.unisdk.common.bean.TransferOrder;
import org.dromara.daxpay.unisdk.common.bean.UniTransferOrder;
import java.util.Map;
@@ -22,7 +22,7 @@ public interface TransferService {
* @param transferOrder 转账订单
* @return 结果
*/
Map<String, Object> transfer(TransferOrder transferOrder);
Map<String, Object> transfer(UniTransferOrder transferOrder);
/**
* 转账查询

View File

@@ -16,7 +16,7 @@ import java.util.Map;
* date 2016-5-18 14:09:01
* </pre>
*/
public interface PayService<PC extends PayConfigStorage> {
public interface UniPayService<PC extends PayConfigStorage> {
/**
@@ -25,7 +25,7 @@ public interface PayService<PC extends PayConfigStorage> {
* @param payConfigStorage 支付配置
* @return 支付服务
*/
PayService setPayConfigStorage(PC payConfigStorage);
UniPayService<PC> setPayConfigStorage(PC payConfigStorage);
/**
* 获取支付配置
@@ -47,7 +47,7 @@ public interface PayService<PC extends PayConfigStorage> {
* @param configStorage http请求配置
* @return 支付服务
*/
PayService setRequestTemplateConfigStorage(HttpConfigStorage configStorage);
UniPayService<PC> setRequestTemplateConfigStorage(HttpConfigStorage configStorage);
/**
* 回调校验
@@ -64,9 +64,9 @@ public interface PayService<PC extends PayConfigStorage> {
* @param order 支付订单
* @param <O> 预订单类型
* @return 订单信息
* @see PayOrder 支付订单信息
* @see UniOrder 支付订单信息
*/
<O extends PayOrder> Map<String, Object> orderInfo(O order);
<O extends UniOrder> Map<String, Object> orderInfo(O order);
/**
* 页面转跳支付 返回对应页面重定向信息
@@ -75,7 +75,7 @@ public interface PayService<PC extends PayConfigStorage> {
* @param <O> 预订单类型
* @return 对应页面重定向信息
*/
<O extends PayOrder> String toPay(O order);
<O extends UniOrder> String toPay(O order);
/**
* app支付
@@ -84,7 +84,7 @@ public interface PayService<PC extends PayConfigStorage> {
* @param <O> 预订单类型
* @return 对应app所需参数信息
*/
<O extends PayOrder> Map<String, Object> app(O order);
<O extends UniOrder> Map<String, Object> app(O order);
/**
* 创建签名
@@ -139,7 +139,7 @@ public interface PayService<PC extends PayConfigStorage> {
* @param <O> 预订单类型
* @return 返回二维码信息,支付时需要的
*/
<O extends PayOrder> String getQrPay(O order);
<O extends UniOrder> String getQrPay(O order);
/**
* 小程序支付返回小程序所需的订单构建信息
@@ -148,7 +148,7 @@ public interface PayService<PC extends PayConfigStorage> {
* @param <O> 预订单类型
* @return 返回支付结果
*/
<O extends PayOrder> Map<String, Object> jsApi(O order);
<O extends UniOrder> Map<String, Object> jsApi(O order);
/**
* 刷卡付,pos主动扫码付款(条码付)
* 刷脸付
@@ -157,7 +157,7 @@ public interface PayService<PC extends PayConfigStorage> {
* @param <O> 预订单类型
* @return 返回支付结果
*/
<O extends PayOrder> Map<String, Object> microPay(O order);
<O extends UniOrder> Map<String, Object> microPay(O order);
/**
@@ -195,7 +195,7 @@ public interface PayService<PC extends PayConfigStorage> {
* @param refundOrder 退款订单信息
* @return 返回支付方申请退款后的结果
*/
RefundResult refund(RefundOrder refundOrder);
RefundResult refund(UniRefundOrder refundOrder);
/**
@@ -204,7 +204,7 @@ public interface PayService<PC extends PayConfigStorage> {
* @param refundOrder 退款订单单号信息
* @return 返回支付方查询退款后的结果
*/
Map<String, Object> refundquery(RefundOrder refundOrder);
Map<String, Object> refundquery(UniRefundOrder refundOrder);
/**
* 下载对账单
@@ -231,7 +231,7 @@ public interface PayService<PC extends PayConfigStorage> {
* @param order 转账订单
* @return 对应的转账结果
*/
Map<String, Object> transfer(TransferOrder order);
Map<String, Object> transfer(UniTransferOrder order);
/**
* 回调处理
@@ -246,7 +246,7 @@ public interface PayService<PC extends PayConfigStorage> {
* 设置支付消息处理器,这里用于处理具体的支付业务
*
* @param handler 消息处理器
* 配合{@link org.dromara.daxpay.unisdk.common.api.PayService#payBack(NoticeRequest)}进行使用
* 配合{@link UniPayService#payBack(NoticeRequest)}进行使用
* <p>
* 默认使用{@link org.dromara.daxpay.unisdk.common.api.DefaultPayMessageHandler }进行实现
*/
@@ -256,7 +256,7 @@ public interface PayService<PC extends PayConfigStorage> {
* 设置支付消息处理器,这里用于处理具体的支付业务
*
* @param interceptor 消息拦截器
* 配合{@link org.dromara.daxpay.unisdk.common.api.PayService#payBack(NoticeRequest)}进行使用
* 配合{@link UniPayService#payBack(NoticeRequest)}进行使用
* <p>
* 默认使用{@link org.dromara.daxpay.unisdk.common.api.DefaultPayMessageHandler }进行实现
*/

View File

@@ -1,21 +0,0 @@
package org.dromara.daxpay.unisdk.common.bean;
/**
* 基础的支付类型
* @author egan
* <pre>
* email egzosn@gmail.com
* date 2016/11/20 0:47
* </pre>
*/
public interface BasePayType {
/**
* 根据支付类型获取交易类型
* @param transactionType 类型值
* @return 交易类型
*/
TransactionType getTransactionType(String transactionType);
}

View File

@@ -6,6 +6,7 @@ import org.dromara.daxpay.unisdk.common.exception.PayErrorException;
import org.dromara.daxpay.unisdk.common.http.HttpRequestTemplate;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* 证书存储类型
@@ -25,10 +26,9 @@ public enum CertStoreType implements CertStore {
*
* @param cert 证书信息
* @return 输入流
* @throws IOException 找不到文件异常
*/
@Override
public InputStream getInputStream(Object cert) throws IOException {
public InputStream getInputStream(Object cert) {
return null;
}
},
@@ -73,11 +73,10 @@ public enum CertStoreType implements CertStore {
*
* @param cert 证书信息
* @return 输入流
* @throws IOException 找不到文件异常
*/
@Override
public InputStream getInputStream(Object cert) throws IOException {
return new ByteArrayInputStream(((String) cert).getBytes("ISO-8859-1"));
public InputStream getInputStream(Object cert) {
return new ByteArrayInputStream(((String) cert).getBytes(StandardCharsets.ISO_8859_1));
}
},
@@ -90,10 +89,9 @@ public enum CertStoreType implements CertStore {
*
* @param cert 证书信息
* @return 输入流
* @throws IOException 找不到文件异常
*/
@Override
public InputStream getInputStream(Object cert) throws IOException {
public InputStream getInputStream(Object cert) {
return (InputStream) cert;
}
},
@@ -107,10 +105,9 @@ public enum CertStoreType implements CertStore {
*
* @param url 获取证书信息的URL
* @return 输入流
* @throws IOException 找不到文件异常
*/
@Override
public InputStream getInputStream(Object url) throws IOException {
public InputStream getInputStream(Object url) {
return new HttpRequestTemplate().getForObject((String) url, InputStream.class);
}
},
@@ -137,8 +134,5 @@ public enum CertStoreType implements CertStore {
}
}
};
}
}

View File

@@ -1,7 +1,7 @@
package org.dromara.daxpay.unisdk.common.bean;
import org.dromara.daxpay.unisdk.common.util.DateUtils;
import org.dromara.daxpay.unisdk.common.util.str.StringUtils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import java.util.Date;
import java.util.Map;
@@ -20,7 +20,7 @@ public final class OrderParaStructure {
}
public static Map<String, Object> loadParameters(Map<String, Object> parameters, String key, String value) {
if (StringUtils.isNotEmpty(value)) {
if (StrUtil.isNotEmpty(value)) {
parameters.put(key, value);
}
return parameters;
@@ -36,7 +36,7 @@ public final class OrderParaStructure {
}
public static Map<String, Object> loadDateParameters(Map<String, Object> parameters, String key, Order order, String datePattern) {
return OrderParaStructure.loadParameters(parameters, key, DateUtils.formatDate((Date) order.getAttr(key), datePattern));
return OrderParaStructure.loadParameters(parameters, key, DateUtil.format((Date) order.getAttr(key), datePattern));
}

View File

@@ -16,5 +16,5 @@ public interface TransferType extends TransactionType{
* @param order 转账订单
* @return 属性对象
*/
Map<String, Object> setAttr(Map<String, Object> attr, TransferOrder order);
Map<String, Object> setAttr(Map<String, Object> attr, UniTransferOrder order);
}

View File

@@ -17,7 +17,7 @@ import java.util.Date;
*/
@Setter
@Getter
public class PayOrder extends AssistOrder {
public class UniOrder extends AssistOrder {
/**
* 商品名称
*/

View File

@@ -17,7 +17,7 @@ import java.util.Date;
*/
@Setter
@Getter
public class RefundOrder extends AssistOrder {
public class UniRefundOrder extends AssistOrder {
/**
* 退款单号每次进行退款的单号此处唯一
*/
@@ -54,23 +54,23 @@ public class RefundOrder extends AssistOrder {
*/
private String refundUrl;
public RefundOrder() {
public UniRefundOrder() {
}
public RefundOrder(String refundNo, String tradeNo, BigDecimal refundAmount) {
public UniRefundOrder(String refundNo, String tradeNo, BigDecimal refundAmount) {
this.refundNo = refundNo;
setTradeNo(tradeNo);
this.refundAmount = refundAmount;
}
public RefundOrder(String tradeNo, String outTradeNo, BigDecimal refundAmount, BigDecimal totalAmount) {
public UniRefundOrder(String tradeNo, String outTradeNo, BigDecimal refundAmount, BigDecimal totalAmount) {
setTradeNo(tradeNo);
setOutTradeNo(outTradeNo);
this.refundAmount = refundAmount;
this.totalAmount = totalAmount;
}
public RefundOrder(String refundNo, String tradeNo, String outTradeNo, BigDecimal refundAmount, BigDecimal totalAmount) {
public UniRefundOrder(String refundNo, String tradeNo, String outTradeNo, BigDecimal refundAmount, BigDecimal totalAmount) {
this.refundNo = refundNo;
setTradeNo(tradeNo);
setOutTradeNo(outTradeNo);

View File

@@ -16,7 +16,7 @@ import java.util.Map;
* date 2018/1/31
* </pre>
*/
public class TransferOrder implements Order {
public class UniTransferOrder implements Order {
/**
* 转账批次订单单号

View File

@@ -14,7 +14,7 @@ import org.dromara.daxpay.unisdk.common.bean.PayOutMessage;
*/
@Getter
public class JsonBuilder extends BaseBuilder<JsonBuilder, PayOutMessage>{
JSONObject json = null;
JSONObject json;
public JsonBuilder(JSONObject json) {
this.json = json;

View File

@@ -1,23 +1,22 @@
package org.dromara.daxpay.unisdk.common.http;
import cn.hutool.core.util.StrUtil;
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;
import org.dromara.daxpay.unisdk.common.util.XML;
import org.dromara.daxpay.unisdk.common.util.str.StringUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
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.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -88,7 +87,7 @@ public class ClientHttpRequest<T> extends HttpEntityEnclosingRequestBase impleme
public ClientHttpRequest(URI uri, MethodType method, Object request, String defaultCharset) {
this(uri, method);
setParameters(request);
if (StringUtils.isNotEmpty(defaultCharset)) {
if (StrUtil.isNotEmpty(defaultCharset)) {
setDefaultCharset(Charset.forName(defaultCharset));
}
@@ -218,7 +217,7 @@ public class ClientHttpRequest<T> extends HttpEntityEnclosingRequestBase impleme
case HttpHeader entity -> {
if (null != entity.getHeaders()) {
if (log.isDebugEnabled()) {
log.debug("header : " + JSON.toJSONString(entity.getHeaders()));
log.debug("header : {}", JSON.toJSONString(entity.getHeaders()));
}
for (Header header : entity.getHeaders()) {
addHeader(header);
@@ -231,7 +230,7 @@ public class ClientHttpRequest<T> extends HttpEntityEnclosingRequestBase impleme
}
if (null != entity.getHeaders()) {
if (log.isDebugEnabled()) {
log.debug("header : " + JSON.toJSONString(entity.getHeaders()));
log.debug("header : {}", JSON.toJSONString(entity.getHeaders()));
}
for (Header header : entity.getHeaders()) {
addHeader(header);
@@ -242,14 +241,14 @@ public class ClientHttpRequest<T> extends HttpEntityEnclosingRequestBase impleme
case Map map -> {
String parameters = getMapToParameters(map);
if (log.isDebugEnabled()) {
log.debug("Parameter : " + parameters);
log.debug("Parameter : {}", parameters);
}
StringEntity entity = new StringEntity(parameters, APPLICATION_FORM_URLENCODED_UTF_8);
setEntity(entity);
}
case String s -> {
if (log.isDebugEnabled()) {
log.debug("Parameter : " + request);
log.debug("Parameter : {}", request);
}
StringEntity entity = new StringEntity(s, APPLICATION_FORM_URLENCODED_UTF_8);
setEntity(entity);
@@ -257,7 +256,7 @@ public class ClientHttpRequest<T> extends HttpEntityEnclosingRequestBase impleme
default -> {
String body = JSON.toJSONString(request);
if (log.isDebugEnabled()) {
log.debug("body : " + request);
log.debug("body : {}", request);
}
StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
setEntity(entity);
@@ -270,14 +269,14 @@ public class ClientHttpRequest<T> extends HttpEntityEnclosingRequestBase impleme
@Override
public T handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
public T handleResponse(HttpResponse response) throws IOException {
final StatusLine statusLine = response.getStatusLine();
final HttpEntity entity = response.getEntity();
if (null == entity){
return null;
}
String[] value = null;
String[] value;
if (null == entity.getContentType()) {
value = new String[]{"application/x-www-form-urlencoded"};
} else {

View File

@@ -1,5 +1,6 @@
package org.dromara.daxpay.unisdk.common.http;
import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
@@ -23,7 +24,6 @@ import org.apache.http.ssl.SSLContexts;
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;
@@ -169,7 +169,7 @@ public class HttpRequestTemplate {
public CredentialsProvider createCredentialsProvider(HttpConfigStorage configStorage) {
if (StringUtils.isBlank(configStorage.getAuthUsername())) {
if (StrUtil.isBlank(configStorage.getAuthUsername())) {
return null;
}
@@ -197,7 +197,7 @@ public class HttpRequestTemplate {
return null;
}
if (log.isInfoEnabled()) {
log.info(String.format("Initialize the PoolingHttpClientConnectionManager -- maxTotal:%s, defaultMaxPerRoute:%s", configStorage.getMaxTotal(), configStorage.getDefaultMaxPerRoute()));
log.info("Initialize the PoolingHttpClientConnectionManager -- maxTotal:{}, defaultMaxPerRoute:{}", configStorage.getMaxTotal(), configStorage.getDefaultMaxPerRoute());
}
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", createSSL(configStorage))
@@ -219,7 +219,7 @@ public class HttpRequestTemplate {
public HttpRequestTemplate setHttpConfigStorage(HttpConfigStorage configStorage) {
this.configStorage = configStorage;
if (null != configStorage && StringUtils.isNotBlank(configStorage.getHttpProxyHost())) {
if (null != configStorage && StrUtil.isNotBlank(configStorage.getHttpProxyHost())) {
//http代理地址设置
httpProxy = new HttpHost(configStorage.getHttpProxyHost(), configStorage.getHttpProxyPort());
;
@@ -424,9 +424,9 @@ public class HttpRequestTemplate {
public <T> ResponseEntity<T> doExecuteEntity(URI uri, Object request, Class<T> responseType, MethodType method) {
if (log.isDebugEnabled()) {
log.debug(String.format("uri:%s, httpMethod:%s ", uri, method.name()));
log.debug("uri:{}, httpMethod:{} ", uri, method.name());
}
ClientHttpRequest<T> httpRequest = new ClientHttpRequest<T>(uri, method, request, null == configStorage ? null : configStorage.getCharset());
ClientHttpRequest<T> httpRequest = new ClientHttpRequest<>(uri, method, request, null == configStorage ? null : configStorage.getCharset());
//判断是否有代理设置
if (null != httpProxy) {
httpRequest.setProxy(httpProxy);

View File

@@ -1,11 +1,11 @@
package org.dromara.daxpay.unisdk.common.http;
import cn.hutool.core.util.StrUtil;
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;
@@ -64,7 +64,7 @@ public class HttpStringEntity extends StringEntity {
}
public void requestIsEmpty(String request) {
if (StringUtils.isEmpty(request)) {
if (StrUtil.isEmpty(request)) {
this.isEmpty = true;
}

View File

@@ -1,10 +1,10 @@
package org.dromara.daxpay.unisdk.common.http;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
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 java.io.UnsupportedEncodingException;
import java.net.URI;
@@ -193,13 +193,13 @@ public final class UriVariables {
private static void putKeyValueToMap(StringBuilder temp, boolean isKey, String key, Map<String, Object> map) {
if (isKey) {
key = temp.toString();
if (key.length() == 0) {
if (key.isEmpty()) {
throw new PayErrorException(new PayException("QString format illegal", "内容格式有误"));
}
map.put(key, "");
}
else {
if (key.length() == 0) {
if (key.isEmpty()) {
throw new PayErrorException(new PayException("QString format illegal", "内容格式有误"));
}
map.put(key, temp.toString());
@@ -227,14 +227,14 @@ public final class UriVariables {
* @return 去除域名的标准url
*/
public static String getCanonicalUrl(String url) {
if (StringUtils.isEmpty(url)) {
if (StrUtil.isEmpty(url)) {
return url;
}
try {
URI uri = new URI(url);
String path = uri.getPath();
String encodedQuery = uri.getQuery();
if (StringUtils.isNotEmpty(encodedQuery)) {
if (StrUtil.isNotEmpty(encodedQuery)) {
path += QUESTION.concat(encodedQuery);
}
return path;

View File

@@ -1,146 +0,0 @@
package org.dromara.daxpay.unisdk.common.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.Args;
import java.lang.ref.SoftReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
/**
* 日期转换运算工具
*
* @author egan
* <pre>
* email egzosn@gmail.com
* date 2018-11-21 16:43:20
* </pre>
*/
@Slf4j
public final class DateUtils {
private DateUtils() {
}
static final class DateFormatHolder {
private static final ThreadLocal<SoftReference<Map<String, SimpleDateFormat>>> THREADLOCAL_FORMATS = new ThreadLocal<SoftReference<Map<String, SimpleDateFormat>>>();
DateFormatHolder() {
}
public static SimpleDateFormat formatFor(String pattern) {
SoftReference<Map<String, SimpleDateFormat>> ref = THREADLOCAL_FORMATS.get();
Map<String, SimpleDateFormat> formats = ref == null ? null : ref.get();
if (formats == null) {
formats = new HashMap<String, SimpleDateFormat>();
THREADLOCAL_FORMATS.set(new SoftReference(formats));
}
SimpleDateFormat format = formats.get(pattern);
if (format == null) {
format = new SimpleDateFormat(pattern);
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
((Map) formats).put(pattern, format);
}
return format;
}
public static void clearThreadLocal() {
THREADLOCAL_FORMATS.remove();
}
}
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String YYYY_MM_DD_T_HH_MM_SS_SSSXXX = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
public static final String YYYY_MM_DD_T_HH_MM_SS_XX = "yyyy-MM-dd'T'HH:mm:ssXXX";
public static final String YYYY_MM_DD = "yyyy-MM-dd";
public static final String YYYYMMDD = "yyyyMMdd";
public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static final String MMDD = "MMdd";
public static final String YYYYMM = "yyyyMM";
public static final String YYYY_MM = "yyyy-MM";
public static String formatDate(Date date, String pattern) {
Args.notNull(date, "Date");
Args.notNull(pattern, "Pattern");
SimpleDateFormat formatFor = DateFormatHolder.formatFor(pattern);
return formatFor.format(date);
}
public static Date parseDate(String date, String pattern) {
Args.notNull(date, "Date");
Args.notNull(pattern, "Pattern");
SimpleDateFormat formatFor = DateFormatHolder.formatFor(pattern);
try {
return formatFor.parse(date);
}
catch (ParseException e) {
log.error("", e);
}
return null;
}
public static Date parse(String date) {
return parseDate(date, YYYY_MM_DD_HH_MM_SS);
}
public static String format(Date date) {
return formatDate(date, YYYY_MM_DD_HH_MM_SS);
}
public static Date parseDay(String date) {
return parseDate(date, YYYY_MM_DD);
}
public static String formatDay(Date date) {
return formatDate(date, YYYY_MM_DD);
}
/**
* 剩余分钟数
*
* @param date 结束点日期
* @return 分钟数
*/
public static long minutesRemaining(Date date) {
return (date.getTime() / 1000 / 60 - DateUtils.toEpochSecond() / 60);
}
/**
* 剩余小时
*
* @param date 结束点日期
* @return 小时数
*/
public static long remainingHours(Date date) {
return minutesRemaining(date) / 60;
}
/**
* 剩余天数
*
* @param date 结束点日期
* @return 天数
*/
public static long remainingDays(Date date) {
return remainingHours(date) / 24;
}
/**
* 将此日期时间转换为从epoch开始的秒数
*
* @return epoch开始的秒数
*/
public static long toEpochSecond() {
return System.currentTimeMillis() / 1000;
}
}

View File

@@ -1,5 +1,8 @@
package org.dromara.daxpay.unisdk.common.util;
import cn.hutool.core.util.StrUtil;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
@@ -15,7 +18,7 @@ public class Util {
*/
public static byte[] intToBytes(int num) {
byte[] bytes = new byte[4];
bytes[0] = (byte) (0xff & (num >> 0));
bytes[0] = (byte) (0xff & (num));
bytes[1] = (byte) (0xff & (num >> 8));
bytes[2] = (byte) (0xff & (num >> 16));
bytes[3] = (byte) (0xff & (num >> 24));
@@ -31,7 +34,7 @@ public class Util {
public static int byteToInt(byte[] bytes) {
int num = 0;
int temp;
temp = (0x000000ff & (bytes[0])) << 0;
temp = (0x000000ff & (bytes[0]));
num = num | temp;
temp = (0x000000ff & (bytes[1])) << 8;
num = num | temp;
@@ -42,6 +45,23 @@ public class Util {
return num;
}
/**
* @param content 需要加密串
* @param charset 字符集
* @return 加密后的字节数组
*/
public static byte[] getContentBytes(String content, String charset) {
if (StrUtil.isEmpty(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException("转码过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
/**
* 长整形转换成网络传输的字节流(字节数组)型数据
*
@@ -337,14 +357,14 @@ public class Util {
int result = 0;
for (int i = max; i > 0; i--) {
char c = hex.charAt(i - 1);
int algorism = 0;
int algorism;
if (c >= '0' && c <= '9') {
algorism = c - '0';
}
else {
algorism = c - 55;
}
result += Math.pow(16, max - i) * algorism;
result += (int) (Math.pow(16, max - i) * algorism);
}
return result;
}
@@ -433,7 +453,7 @@ public class Util {
for (int i = max; i > 0; i--) {
char c = binary.charAt(i - 1);
int algorism = c - '0';
result += Math.pow(2, max - i) * algorism;
result += (int) (Math.pow(2, max - i) * algorism);
}
return result;
}
@@ -465,10 +485,8 @@ public class Util {
* @return 补充结果
*/
public static String patchHexString(String str, int maxLength) {
StringBuilder temp = new StringBuilder();
temp.append("0".repeat(Math.max(0, maxLength - str.length())));
temp.append(str);
return temp.toString();
return "0".repeat(Math.max(0, maxLength - str.length())) +
str;
}
@@ -557,7 +575,7 @@ public class Util {
public static byte[] subByte(byte[] input, int startIndex, int length) {
byte[] bt = new byte[length];
System.arraycopy(input, 0 + startIndex, bt, 0, length);
System.arraycopy(input, startIndex, bt, 0, length);
return bt;
}

View File

@@ -1,12 +1,12 @@
package org.dromara.daxpay.unisdk.common.util;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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 org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@@ -27,6 +27,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
@@ -87,7 +88,7 @@ public class XML {
*/
public static JSONObject toJSONObject(String content, Charset charset) {
if (StringUtils.isEmpty(content)) {
if (StrUtil.isEmpty(content)) {
return null;
}
return toJSONObject(content.getBytes(charset));
@@ -123,10 +124,10 @@ public class XML {
*/
public static <T> T toBean(String content, Class<T> clazz) {
if (StringUtils.isEmpty(content)) {
if (StrUtil.isEmpty(content)) {
return null;
}
try (InputStream in = new ByteArrayInputStream(content.getBytes("UTF-8"))) {
try (InputStream in = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))) {
return inputStream2Bean(in, clazz);
}
catch (IOException e) {
@@ -220,29 +221,27 @@ public class XML {
if (null == m) {
m = new JSONObject();
}
try {
try (in) {
DocumentBuilder documentBuilder = newDocumentBuilder();
Document doc = documentBuilder.parse(in);
doc.getDocumentElement().normalize();
NodeList children = doc.getDocumentElement().getChildNodes();
doc.getDocumentElement()
.normalize();
NodeList children = doc.getDocumentElement()
.getChildNodes();
for (int idx = 0; idx < children.getLength(); ++idx) {
Node node = children.item(idx);
NodeList nodeList = node.getChildNodes();
int length = nodeList.getLength();
if (node.getNodeType() == Node.ELEMENT_NODE && (length > 1 || length == 1 && nodeList.item(0).hasChildNodes())) {
if (node.getNodeType() == Node.ELEMENT_NODE && (length > 1 || length == 1 && nodeList.item(0)
.hasChildNodes())) {
m.put(node.getNodeName(), getChildren(nodeList));
}
else if (node.getNodeType() == Node.ELEMENT_NODE) {
} else if (node.getNodeType() == Node.ELEMENT_NODE) {
m.put(node.getNodeName(), node.getTextContent());
}
}
}
catch (ParserConfigurationException | SAXException e) {
} catch (ParserConfigurationException | SAXException e) {
throw new PayErrorException(new PayException("XML failure", "XML解析失败\n" + e.getMessage()));
}
finally {
in.close();
}
return m;
}

View File

@@ -14,8 +14,8 @@
*/
package org.dromara.daxpay.unisdk.common.util.sign;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.daxpay.unisdk.common.util.str.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -63,7 +63,7 @@ public class CertDescriptor {
*/
private static X509Certificate initCert(InputStream certIn) {
X509Certificate encryptCertTemp = null;
CertificateFactory cf = null;
CertificateFactory cf;
try {
cf = CertificateFactory.getInstance("X.509");
encryptCertTemp = (X509Certificate) cf.generateCertificate(certIn);
@@ -97,8 +97,7 @@ public class CertDescriptor {
*/
private static X509Certificate initCert(String path) {
X509Certificate encryptCertTemp = null;
CertificateFactory cf = null;
FileInputStream in = null;
FileInputStream in;
try {
in = new FileInputStream(path);
encryptCertTemp = initCert(in);
@@ -227,7 +226,7 @@ public class CertDescriptor {
log.warn("Load RSA CertPath,Pwd=[{}],type=[{}]", keyPwd, type);
}
char[] nPassword = null;
char[] nPassword;
nPassword = null == keyPwd || keyPwd.trim()
.isEmpty() ? null : keyPwd.toCharArray();
ks.load(fxKeyFile, nPassword);
@@ -257,7 +256,7 @@ public class CertDescriptor {
* @return
*/
private String getCertIdIdByStore(KeyStore keyStore) {
Enumeration<String> aliasenum = null;
Enumeration<String> aliasenum;
try {
aliasenum = keyStore.aliases();
String keyAlias = null;
@@ -281,7 +280,7 @@ public class CertDescriptor {
* @param certPath 证书地址
*/
public void initPublicCert(String certPath) {
if (!StringUtils.isEmpty(certPath)) {
if (!StrUtil.isEmpty(certPath)) {
publicKeyCert = initCert(certPath);
if (log.isInfoEnabled()) {
log.info("Load PublicKeyCert Successful");
@@ -315,7 +314,7 @@ public class CertDescriptor {
* @param certPath 证书地址
*/
public void initRootCert(String certPath) {
if (!StringUtils.isEmpty(certPath)) {
if (!StrUtil.isEmpty(certPath)) {
try {
initRootCert(new FileInputStream(certPath));
}

View File

@@ -1,6 +1,6 @@
package org.dromara.daxpay.unisdk.common.util.sign;
import org.dromara.daxpay.unisdk.common.util.str.StringUtils;
import cn.hutool.core.util.StrUtil;
import org.apache.http.message.BasicNameValuePair;
import java.util.*;
@@ -83,7 +83,7 @@ public final class SignTextUtils {
}
sb.append(entry.getKey()).append("=").append(valStr).append(separator);
}
if (sb.length() > 0 && !"".equals(separator)) {
if (!sb.isEmpty() && !"".equals(separator)) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
@@ -98,7 +98,7 @@ public final class SignTextUtils {
private static String sortMapParameterText(Map<String, Object> parameters, String separator, boolean ignoreNullValue, String... ignoreKey) {
StringBuilder sb = new StringBuilder();
// TODO 2016/11/11 10:14 author: egan 未排序须处理
List<String> keys = new ArrayList<String>(parameters.keySet());
List<String> keys = new ArrayList<>(parameters.keySet());
//排序
Collections.sort(keys);
for (String k : keys) {
@@ -120,12 +120,12 @@ public final class SignTextUtils {
else {
valueStr = new StringBuilder(o.toString());
}
if (StringUtils.isBlank(valueStr.toString()) || (null != ignoreKey && Arrays.binarySearch(ignoreKey, k) >= 0)) {
if (StrUtil.isBlank(valueStr.toString()) || (null != ignoreKey && Arrays.binarySearch(ignoreKey, k) >= 0)) {
continue;
}
sb.append(k).append("=").append(valueStr).append(separator);
}
if (sb.length() > 0) {
if (!sb.isEmpty()) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
@@ -156,18 +156,9 @@ public final class SignTextUtils {
}
}
return StringUtils.isBlank(sb.toString()) ? "" : sb.deleteCharAt(sb.length() - 1).toString();
return StrUtil.isBlank(sb.toString()) ? "" : sb.deleteCharAt(sb.length() - 1).toString();
}
/**
* 获取随机字符串
*
* @return 随机字符串
*/
public static String randomStr() {
return StringUtils.randomStr();
}
}

View File

@@ -1,25 +0,0 @@
package org.dromara.daxpay.unisdk.common.util.sign.encrypt;
/**
* Base64
* @author egan
* <pre>
* email egzosn@gmail.com
*
* create 2019/05/15 12:50
* </pre>
*/
public class Base64 {
private Base64() {}
public static byte[] decode(String str) {
return org.apache.commons.codec.binary.Base64.decodeBase64(str);
}
public static String encode(byte[] bytes) {
return org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);
}
}

View File

@@ -29,7 +29,7 @@ public class HmacSha256 {
* @return 签名值
*/
public static String createSign(String content, String key, String characterEncoding) {
Mac sha256HMAC = null;
Mac sha256HMAC;
try {
sha256HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(characterEncoding), "HmacSHA256");

View File

@@ -1,10 +1,9 @@
package org.dromara.daxpay.unisdk.common.util.sign.encrypt;
import org.dromara.daxpay.unisdk.common.util.str.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import static org.dromara.daxpay.unisdk.common.util.str.StringUtils.getContentBytes;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import org.dromara.daxpay.unisdk.common.util.Util;
/**
* MD5签名工具
@@ -26,7 +25,7 @@ public class MD5 {
public static String sign(String text, String key, String inputCharset) {
//拼接key
text = text + key;
return DigestUtils.md5Hex(getContentBytes(text, inputCharset));
return DigestUtil.md5Hex(Util.getContentBytes(text, inputCharset));
}
/**
@@ -40,7 +39,7 @@ public class MD5 {
*/
public static boolean verify(String text, String sign, String key, String inputCharset) {
//判断是否一样
return StringUtils.equals(sign(text, key, inputCharset).toUpperCase(), sign.toUpperCase());
return StrUtil.equals(sign(text, key, inputCharset).toUpperCase(), sign.toUpperCase());
}

View File

@@ -1,6 +1,7 @@
package org.dromara.daxpay.unisdk.common.util.sign.encrypt;
import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -220,7 +221,7 @@ public class RSA {
byte[] buf = new byte[128];
int bufl;
while ((bufl = ins.read(buf)) != -1) {
byte[] block = null;
byte[] block;
if (buf.length == bufl) {
block = buf;
@@ -286,7 +287,7 @@ public class RSA {
public static PublicKey getPublicKey(InputStream inputStream, String keyAlgorithm) throws IOException, GeneralSecurityException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));) {
StringBuilder sb = new StringBuilder();
String readLine = null;
String readLine;
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;

View File

@@ -1,6 +1,8 @@
package org.dromara.daxpay.unisdk.common.util.sign.encrypt;
import cn.hutool.core.codec.Base64;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;

View File

@@ -1,7 +1,8 @@
package org.dromara.daxpay.unisdk.common.util.sign.encrypt;
import org.dromara.daxpay.unisdk.common.util.str.StringUtils;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.dromara.daxpay.unisdk.common.util.Util;
/**
@@ -28,7 +29,7 @@ public class SHA1 {
public static String sign(String text, String key, String inputCharset) {
//拼接key
text = text + key;
return DigestUtils.sha1Hex( StringUtils.getContentBytes(text, inputCharset));
return DigestUtils.sha1Hex(Util.getContentBytes(text, inputCharset));
}
@@ -43,7 +44,7 @@ public class SHA1 {
*/
public static boolean verify(String text, String sign, String key, String inputCharset) {
//判断是否一样
return StringUtils.equals(sign(text, key, inputCharset).toUpperCase(), sign.toUpperCase());
return StrUtil.equals(sign(text, key, inputCharset).toUpperCase(), sign.toUpperCase());
}
}

View File

@@ -1,5 +1,6 @@
package org.dromara.daxpay.unisdk.common.util.sign.encrypt;
import cn.hutool.core.util.StrUtil;
import org.dromara.daxpay.unisdk.common.util.str.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
@@ -42,7 +43,7 @@ public class SHA256 {
*/
public static boolean verify(String text, String sign, String key, String inputCharset) {
//判断是否一样
return StringUtils.equals(sign(text, key, inputCharset).toUpperCase(), sign.toUpperCase());
return StrUtil.equals(sign(text, key, inputCharset).toUpperCase(), sign.toUpperCase());
}
}

View File

@@ -167,10 +167,8 @@ public class SM3 {
}
private static int P0(int X) {
int y = rotateLeft(X, 9);
y = bitCycleLeft(X, 9);
int z = rotateLeft(X, 17);
z = bitCycleLeft(X, 17);
int y = bitCycleLeft(X, 9);
int z = bitCycleLeft(X, 17);
return X ^ y ^ z;
}
@@ -193,7 +191,7 @@ public class SM3 {
k += 1;
byte[] padd = new byte[k / 8];
padd[0] = (byte) 0x80;
long n = in.length * 8 + bLen * 512;
long n = in.length * 8L + bLen * 512L;
byte[] out = new byte[in.length + k / 8 + 64 / 8];
int pos = 0;
System.arraycopy(in, 0, out, 0, in.length);

View File

@@ -14,7 +14,7 @@ public class SM3Digest {
/**
* 缓冲区长度
*/
private static final int BUFFER_LENGTH = BLOCK_LENGTH * 1;
private static final int BUFFER_LENGTH = BLOCK_LENGTH;
/**
* 缓冲区

View File

@@ -3,126 +3,19 @@ package org.dromara.daxpay.unisdk.common.util.str;
import cn.hutool.core.util.StrUtil;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
/**
* Created by ZaoSheng on 2016/6/4.
*/
public class StringUtils {
/**
* 比较两个字符串(大小写敏感)。
* <pre>
* StringUtil.equals(null, null) = true
* StringUtil.equals(null, "abc") = false
* StringUtil.equals("abc", null) = false
* StringUtil.equals("abc", "abc") = true
* StringUtil.equals("abc", "ABC") = false
* </pre>
*
* @param str1 要比较的字符串1
* @param str2 要比较的字符串2
* @return 如果两个字符串相同,或者都是<code>null</code>,则返回<code>true</code>
*/
public static boolean equals(String str1, String str2) {
if (str1 == null) {
return str2 == null;
}
return str1.equals(str2);
}
// Empty checks
//-----------------------------------------------------------------------
/**
* <p>Checks if a CharSequence is empty ("") or null.</p>
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is empty or null
*/
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
/**
* <p>Checks if a CharSequence is not empty ("") and not null.</p>
*
* <pre>
* StringUtils.isNotEmpty(null) = false
* StringUtils.isNotEmpty("") = false
* StringUtils.isNotEmpty(" ") = true
* StringUtils.isNotEmpty("bob") = true
* StringUtils.isNotEmpty(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is not empty and not null
*/
public static boolean isNotEmpty(CharSequence cs) {
return !StrUtil.isEmpty(cs);
}
/**
* <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is null, empty or whitespace
* @since 2.0
*/
public static boolean isBlank(CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p>
*
* <pre>
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
* StringUtils.isNotBlank(" ") = false
* StringUtils.isNotBlank("bob") = true
* StringUtils.isNotBlank(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is
* not empty and not null and not whitespace
*/
public static boolean isNotBlank(CharSequence cs) {
return !StringUtils.isBlank(cs);
}
/**
* @param content 需要加密串
* @param charset 字符集
* @return 加密后的字节数组
*/
public static byte[] getContentBytes(String content, String charset) {
if (StringUtils.isEmpty(charset)) {
if (StrUtil.isEmpty(charset)) {
return content.getBytes();
}
try {
@@ -133,45 +26,4 @@ public class StringUtils {
}
}
/**
* 对 subject body 进行 trim 运算,
* 以防止在签名是可能造成的签名错误问题
*
* @param str 字符
* @return 去除空格之后的字符
*/
public static String tryTrim(String str) {
return str == null ? null : str.trim();
}
/**
* 字符串数组拼接为字符串
*
* @param separator 分隔符
* @param str 字符数组
* @return 字符串
*/
public static String joining(String separator, String... str) {
StringBuilder builder = new StringBuilder();
for (String s : str) {
if (null == s) {
continue;
}
builder.append(s).append(separator);
}
return builder.toString();
}
/**
* 获取随机字符串
*
* @return 随机字符串
*/
public static String randomStr() {
return UUID.randomUUID().toString().replace("-", "");
}
}