From 56b4d3fcfc9edf19659821d983113840d1acbe14 Mon Sep 17 00:00:00 2001 From: hejinbo Date: Mon, 9 Oct 2023 18:18:04 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E7=94=A8=E5=8D=B0=E6=A8=A1=E6=8B=9F?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../wisdomarbitrate/AdjudicationController.java | 9 +++++++++ .../wisdomarbitrate/service/IAdjudicationService.java | 2 ++ .../service/impl/AdjudicationServiceImpl.java | 8 ++++++++ 3 files changed, 19 insertions(+) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/wisdomarbitrate/AdjudicationController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/wisdomarbitrate/AdjudicationController.java index 2dfd99d..213e195 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/wisdomarbitrate/AdjudicationController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/wisdomarbitrate/AdjudicationController.java @@ -83,4 +83,13 @@ public class AdjudicationController extends BaseController { ,String apptrackingNum,String restrackingNum){ return adjudicationService.service(id,appEmail,resEmail,apptrackingNum,restrackingNum); } + /** + * 用印(暂时只改案件状态) + * @param caseApplication + * @return + */ + @PostMapping("/stamp") + public AjaxResult stamp(@Validated @RequestBody CaseApplication caseApplication){ + return adjudicationService.stamp(caseApplication); + } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/wisdomarbitrate/service/IAdjudicationService.java b/ruoyi-system/src/main/java/com/ruoyi/wisdomarbitrate/service/IAdjudicationService.java index 935b0a2..773fc61 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/wisdomarbitrate/service/IAdjudicationService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/wisdomarbitrate/service/IAdjudicationService.java @@ -16,4 +16,6 @@ public interface IAdjudicationService { AjaxResult service(Long id, String appEmail, String resEmail, String apptrackingNum, String restrackingNum); + AjaxResult stamp(CaseApplication caseApplication); + } diff --git a/ruoyi-system/src/main/java/com/ruoyi/wisdomarbitrate/service/impl/AdjudicationServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/wisdomarbitrate/service/impl/AdjudicationServiceImpl.java index f2059f1..e4e8fff 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/wisdomarbitrate/service/impl/AdjudicationServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/wisdomarbitrate/service/impl/AdjudicationServiceImpl.java @@ -352,6 +352,14 @@ public class AdjudicationServiceImpl implements IAdjudicationService { return AjaxResult.success("仲裁文书送达成功"); } + @Override + public AjaxResult stamp(CaseApplication caseApplication) { + //更改案件状态(暂时) + caseApplication.setCaseStatus(CaseApplicationConstants.ARBITRATION_DELIVERY); + caseApplicationMapper.submitCaseApplication(caseApplication); + return AjaxResult.success("用印成功,案件状态已改为待仲裁文书送达"); + } + public static void main(String[] args) { try { List fileList = new ArrayList<>(); From 4d4ab28c40e2d8699c800f6895b67bac5060059d Mon Sep 17 00:00:00 2001 From: hejinbo Date: Tue, 10 Oct 2023 16:22:24 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=20=E8=8E=B7=E5=8F=96=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E5=9C=B0=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AdjudicationController.java | 11 +- ruoyi-common/pom.xml | 5 +- .../ruoyi/common/config/EsignDemoConfig.java | 13 + .../common/constant/EsignEncryption.java | 371 +++++++++++++ .../common/constant/EsignHeaderConstant.java | 26 + .../common/constant/EsignHttpCfgHelper.java | 486 ++++++++++++++++++ .../common/constant/FileTransformation.java | 284 ++++++++++ .../core/domain/entity/EsignCoreSdkInfo.java | 24 + .../core/domain/entity/EsignHttpResponse.java | 24 + .../ruoyi/common/enums/EsignRequestType.java | 39 ++ .../common/exception/EsignDemoException.java | 36 ++ .../ruoyi/common/utils/EsignHttpHelper.java | 178 +++++++ .../common/utils/bean/EsignFileBean.java | 57 ++ .../common/utils/file/SaaSAPIFileUtils.java | 43 ++ 14 files changed, 1588 insertions(+), 9 deletions(-) create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/config/EsignDemoConfig.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/constant/EsignEncryption.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/constant/EsignHeaderConstant.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/constant/EsignHttpCfgHelper.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/constant/FileTransformation.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/EsignCoreSdkInfo.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/EsignHttpResponse.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/enums/EsignRequestType.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/exception/EsignDemoException.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/utils/EsignHttpHelper.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/utils/bean/EsignFileBean.java create mode 100644 ruoyi-common/src/main/java/com/ruoyi/common/utils/file/SaaSAPIFileUtils.java diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/wisdomarbitrate/AdjudicationController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/wisdomarbitrate/AdjudicationController.java index d934d51..cbc0f7b 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/wisdomarbitrate/AdjudicationController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/wisdomarbitrate/AdjudicationController.java @@ -27,17 +27,12 @@ public class AdjudicationController extends BaseController { /** * 裁决书送达(电子邮件) - * @param id 案件id - * @param appEmail 申请人邮箱 - * @param resEmail 被申请人邮箱 - * @param apptrackingNum 申请人快递单号 - * @param restrackingNum 被申请人快递单号 + * @param bookSendVO * @return */ @PostMapping("/delivery") - public AjaxResult sendDocumentByEmail(Long id,String appEmail,String resEmail - ,String apptrackingNum,String restrackingNum){ - return adjudicationService.sendDocumentByEmail(id,appEmail,resEmail,apptrackingNum,restrackingNum); + public AjaxResult sendDocumentByEmail(@RequestBody BookSendVO bookSendVO){ + return adjudicationService.sendDocumentByEmail(bookSendVO.getId(),bookSendVO.getAppEmail(),bookSendVO.getResEmail(),bookSendVO.getApptrackingNum(),bookSendVO.getRestrackingNum()); } /** diff --git a/ruoyi-common/pom.xml b/ruoyi-common/pom.xml index 3b55c2b..77e53b1 100644 --- a/ruoyi-common/pom.xml +++ b/ruoyi-common/pom.xml @@ -183,7 +183,10 @@ mail 1.4.7 - + + org.apache.httpcomponents + httpclient + diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/config/EsignDemoConfig.java b/ruoyi-common/src/main/java/com/ruoyi/common/config/EsignDemoConfig.java new file mode 100644 index 0000000..f9888e2 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/config/EsignDemoConfig.java @@ -0,0 +1,13 @@ +package com.ruoyi.common.config; + +public class EsignDemoConfig { + + // 应用ID + public static final String EsignAppId = "7438987614"; + // 应用密钥 + public static final String EsignAppSecret = "9d7844f13830931037772b9d20cf1529"; + // e签宝接口调用域名(模拟环境) + public static final String EsignHost = "https://smlopenapi.esign.cn"; + // e签宝接口调用域名(正式环境) + // public static final String EsignHost = "https://openapi.esign.cn"; +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/constant/EsignEncryption.java b/ruoyi-common/src/main/java/com/ruoyi/common/constant/EsignEncryption.java new file mode 100644 index 0000000..ade398b --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/constant/EsignEncryption.java @@ -0,0 +1,371 @@ +/* + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.ruoyi.common.constant; +import com.ruoyi.common.exception.EsignDemoException; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.message.BasicNameValuePair; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.UnsupportedEncodingException; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.Collator; +import java.text.MessageFormat; +import java.util.*; + +/** + * @description 请求数据通用处理类 + * @author 澄泓 + * @date 2020年10月22日 下午14:25:31 + * @since JDK1.7 + */ +public class EsignEncryption { + + /** + * 不允许外部创建实例 + */ + private EsignEncryption(){} + + /** + * 拼接待签名字符串 + * @param httpMethod + * @param url + * @return + */ + public static String appendSignDataString(String httpMethod, String contentMd5,String accept,String contentType,String headers,String date, String url) throws EsignDemoException { + StringBuffer sb = new StringBuffer(); + sb.append(httpMethod).append("\n").append(accept).append("\n").append(contentMd5).append("\n") + .append(contentType).append("\n"); + + if ("".equals(date) || date == null) { + sb.append("\n"); + } else { + sb.append(date).append("\n"); + } + if ("".equals(headers) || headers == null) { + sb.append(url); + } else { + sb.append(headers).append("\n").append(url); + } + return new String(sb); + } + + /*** + * Content-MD5的计算方法 + * @param str 待计算的消息 + * @return MD5计算后摘要值的Base64编码(ContentMD5) + * @throws EsignDemoException 加密过程中的异常信息 + */ + public static String doContentMD5(String str) throws EsignDemoException { + byte[] md5Bytes = null; + MessageDigest md5 = null; + String contentMD5 = null; + try { + md5 = MessageDigest.getInstance("MD5"); + // 计算md5函数 + md5.update(str.getBytes("UTF-8")); + // 获取文件MD5的二进制数组(128位) + md5Bytes = md5.digest(); + // 把MD5摘要后的二进制数组md5Bytes使用Base64进行编码(而不是对32位的16进制字符串进行编码) + contentMD5 = Base64.encodeBase64String(md5Bytes); + + } catch (NoSuchAlgorithmException e) { + EsignDemoException ex = new EsignDemoException("不支持此算法",e); + ex.initCause(e); + throw ex; + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return contentMD5; + } + + /*** + * 计算请求签名值-HmacSHA256摘要 + * @param message 待签名字符串 + * @param secret 密钥APP KEY + * @return reqSignature HmacSHA256计算后摘要值的Base64编码 + * @throws EsignDemoException 加密过程中的异常信息 + */ + public static String doSignatureBase64(String message, String secret) throws EsignDemoException { + String algorithm = "HmacSHA256"; + Mac hmacSha256; + String digestBase64 = null; + try { + hmacSha256 = Mac.getInstance(algorithm); + byte[] keyBytes = secret.getBytes("UTF-8"); + byte[] messageBytes = message.getBytes("UTF-8"); + hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, algorithm)); + // 使用HmacSHA256对二进制数据消息Bytes计算摘要 + byte[] digestBytes = hmacSha256.doFinal(messageBytes); + // 把摘要后的结果digestBytes使用Base64进行编码 + digestBase64 = Base64.encodeBase64String(digestBytes); + } catch (NoSuchAlgorithmException e) { + EsignDemoException ex = new EsignDemoException("不支持此算法",e); + ex.initCause(e); + throw ex; + } catch (InvalidKeyException e) { + EsignDemoException ex = new EsignDemoException("无效的密钥规范",e); + ex.initCause(e); + throw ex; + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return digestBase64; + } + + /** + * 获取时间戳 + * @return + */ + public static String timeStamp() { + long timeStamp = System.currentTimeMillis(); + return String.valueOf(timeStamp); + } + + /** + * byte字节数组转换成字符串 + * @param b + * @return + */ + public static String byteArrayToHexString(byte[] b) { + StringBuilder hs = new StringBuilder(); + String stmp; + for (int n = 0; b != null && n < b.length; n++) { + stmp = Integer.toHexString(b[n] & 0XFF); + if (stmp.length() == 1) + hs.append('0'); + hs.append(stmp); + } + return hs.toString().toLowerCase(); + } + + /** + * hash散列加密算法 + * @return + */ + public static String Hmac_SHA256(String message,String key) throws EsignDemoException { + byte[] rawHmac=null; + try { + SecretKeySpec sk = new SecretKeySpec(key.getBytes(), "HmacSHA256"); + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(sk); + rawHmac = mac.doFinal(message.getBytes()); + }catch (InvalidKeyException e){ + EsignDemoException ex = new EsignDemoException("无效的密钥规范",e); + ex.initCause(e); + throw ex; + } catch (NoSuchAlgorithmException e) { + EsignDemoException ex = new EsignDemoException("不支持此算法",e); + ex.initCause(e); + throw ex; + }catch (Exception e){ + EsignDemoException ex = new EsignDemoException("hash散列加密算法报错",e); + ex.initCause(e); + throw ex; + }finally { + return byteArrayToHexString(rawHmac); + } + + } + + /** + * MD5加密32位 + */ + public static String MD5Digest(String text) throws EsignDemoException { + byte[] digest=null; + try { + MessageDigest md5 = MessageDigest.getInstance("MD5"); + md5.update(text.getBytes()); + digest = md5.digest(); + }catch (NoSuchAlgorithmException e){ + EsignDemoException ex = new EsignDemoException("不支持此算法",e); + ex.initCause(e); + throw ex; + }finally { + return byteArrayToHexString(digest); + } + + } + + public static void formDataSort(List param) { + Collections.sort(param, new Comparator() { + @Override + public int compare(BasicNameValuePair o1, BasicNameValuePair o2) { + Comparator com = Collator.getInstance(Locale.CHINA); + return com.compare(o1.getName(), o2.getName()); + } + }); + } + + /*** + * 字符串是否为空(含空格校验) + * @param str + * @return + */ + public static boolean isBlank(String str) { + if (null == str || 0 == str.length()) { + return true; + } + + int strLen = str.length(); + + for (int i = 0; i < strLen; i++) { + if (!Character.isWhitespace(str.charAt(i))) { + return false; + } + } + return true; + } + + + /*** + * 对请求URL中的Query参数按照字段名的 ASCII 码从小到大排序(字典排序) + * + * @param apiUrl + * @return 排序后的API接口地址 + * @throws Exception + */ + public static String sortApiUrl(String apiUrl) throws EsignDemoException { + + if (!apiUrl.contains("?")) { + return apiUrl; + } + + int queryIndex = apiUrl.indexOf("?"); + String apiUrlPath =apiUrl.substring(0,queryIndex+1); + String apiUrlQuery = apiUrl.substring(queryIndex+1); + //apiUrlQuery为空时返回 + if(isBlank(apiUrlQuery)){ + return apiUrl.substring(0,apiUrl.length()-1); + } + // 请求URL中Query参数转成Map + Map queryParamsMap = new HashMap(); + String[] params = apiUrlQuery.split("&"); + for (String str : params) { + int index = str.indexOf("="); + String key = str.substring(0, index); + String value = str.substring(index + 1); + if (queryParamsMap.containsKey(key)) { + String msg = MessageFormat.format("请求URL中的Query参数的{0}重复", key); + throw new EsignDemoException(msg); + } + queryParamsMap.put(key, value); + } + + ArrayList queryMapKeys = new ArrayList(); + for (Map.Entry entry : queryParamsMap.entrySet()) { + queryMapKeys.add((String) entry.getKey()); + } + // 按照字段名的 ASCII 码从小到大排序(字典排序) + Collections.sort(queryMapKeys, new Comparator() { + @Override + public int compare(String o1, String o2) { + return (o1.compareToIgnoreCase(o2) == 0 ? -o1.compareTo(o2) : o1.compareToIgnoreCase(o2)); + } + }); + + StringBuffer queryString = new StringBuffer(); + // 构造Query参数键值对值对的格式 + for (int i = 0; i < queryMapKeys.size(); i++) { + String key = queryMapKeys.get(i); + String value = (String) queryParamsMap.get(key); + queryString.append(key); + queryString.append("="); + queryString.append(value); + queryString.append("&"); + } + if (queryString.length() > 0) { + queryString = queryString.deleteCharAt(queryString.length() - 1); + } + + // Query参数排序后的接口请求地址 + StringBuffer sortApiUrl = new StringBuffer(); + sortApiUrl.append(apiUrlPath); + sortApiUrl.append(queryString.toString()); + return sortApiUrl.toString(); + } + + /** + *获取query + * @param apiUrl + * @return + * @throws EsignDemoException + */ + public static ArrayList getQuery(String apiUrl) throws EsignDemoException { + ArrayList BasicNameValuePairList = new ArrayList<>(); + + if (!apiUrl.contains("?")) { + return BasicNameValuePairList; + } + + int queryIndex = apiUrl.indexOf("\\?"); + String apiUrlQuery = apiUrl.substring(queryIndex,apiUrl.length()); + + // 请求URL中Query参数转成Map + Map queryParamsMap = new HashMap(); + String[] params = apiUrlQuery.split("&"); + for (String str : params) { + int index = str.indexOf("="); + String key = str.substring(0, index); + String value = str.substring(index + 1); + if (queryParamsMap.containsKey(key)) { + String msg = MessageFormat.format("请求URL中的Query参数的{0}重复", key); + throw new EsignDemoException(msg); + } + BasicNameValuePairList.add(new BasicNameValuePair(key,value)); + queryParamsMap.put(key, value); + } + return BasicNameValuePairList; + } + /** + * + */ + public static boolean callBackCheck(String timestamp,String requestQuery,String body,String key,String signature){ + String algorithm="HmacSHA256"; + String encoding="UTF-8"; + Mac mac = null; + try { + String data = timestamp + requestQuery + body; + mac = Mac.getInstance(algorithm); + SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(encoding), algorithm); + mac.init(secretKey); + mac.update(data.getBytes(encoding)); + } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) { + e.printStackTrace(); + System.out.println("获取Signature签名信息异常:" + e.getMessage()); + return false; + } + return byte2hex(mac.doFinal()).equalsIgnoreCase(signature); + } + + /*** + * 将byte[]转成16进制字符串 + * + * @param data + * + * @return 16进制字符串 + */ + public static String byte2hex(byte[] data) { + StringBuilder hash = new StringBuilder(); + String stmp; + for (int n = 0; data != null && n < data.length; n++) { + stmp = Integer.toHexString(data[n] & 0XFF); + if (stmp.length() == 1) + hash.append('0'); + hash.append(stmp); + } + return hash.toString(); + } + +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/constant/EsignHeaderConstant.java b/ruoyi-common/src/main/java/com/ruoyi/common/constant/EsignHeaderConstant.java new file mode 100644 index 0000000..ae1e035 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/constant/EsignHeaderConstant.java @@ -0,0 +1,26 @@ +package com.ruoyi.common.constant; +/** + * @description 头部信息常量 + * @author 澄泓 + * @date 2020/10/22 15:05 + * @version JDK1.7 + */ +public enum EsignHeaderConstant { + ACCEPT("*/*"), + DATE(""), + HEADERS( ""), + CONTENTTYPE_FORMDATA("application/x-www-form-urlencoded"), + CONTENTTYPE_JSON("application/json; charset=UTF-8"), + CONTENTTYPE_PDF("application/pdf"), + CONTENTTYPE_STREAM("application/octet-stream"), + AUTHMODE("Signature"); + + private String value; + private EsignHeaderConstant(String value) { + this.value=value; + } + + public String VALUE(){ + return this.value; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/constant/EsignHttpCfgHelper.java b/ruoyi-common/src/main/java/com/ruoyi/common/constant/EsignHttpCfgHelper.java new file mode 100644 index 0000000..78162ed --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/constant/EsignHttpCfgHelper.java @@ -0,0 +1,486 @@ +/* + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.ruoyi.common.constant; +import com.ruoyi.common.core.domain.entity.EsignHttpResponse; +import com.ruoyi.common.enums.EsignRequestType; +import com.ruoyi.common.exception.EsignDemoException; +import org.apache.http.*; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.HttpRequestRetryHandler; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.ConnectTimeoutException; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.LayeredConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.ByteArrayEntity; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.protocol.HttpContext; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.*; +import java.io.IOException; +import java.io.InterruptedIOException; +import java.net.UnknownHostException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * @description Http请求 辅助类 + * @author 澄泓 + * @since JDK1.7 + */ +public class EsignHttpCfgHelper { + + private static Logger LOGGER = LoggerFactory.getLogger(EsignHttpCfgHelper.class); + /** + * 超时时间,默认15000毫秒 + */ + private static int MAX_TIMEOUT = 15000; + /** + * 请求池最大连接数,默认100个 + */ + private static int MAX_TOTAL=100; + /** + * 单域名最大的连接数,默认50个 + */ + private static int ROUTE_MAX_TOTAL=50; + /** + * 请求失败重试次数,默认3次 + */ + private static int MAX_RETRY = 3; + /** + * 是否需要域名校验,默认不需要校验 + */ + private static boolean SSL_VERIFY=false; + + /** + * 正向代理IP + */ + private static String PROXY_IP; + /** + * 正向代理端口,默认8888 + */ + private static int PROXY_PORT=8888; + /** + * 代理协议,默认http + */ + private static String PROXY_AGREEMENT="http"; + + /** + * 是否开启代理,默认false + */ + private static boolean OPEN_PROXY=false; + + /** + * 代理服务器用户名 + */ + private static String PROXY_USERNAME=""; + + /** + * 代理服务器密码 + */ + private static String PROXY_PASSWORD=""; + + + private static PoolingHttpClientConnectionManager connMgr; //连接池 + private static HttpRequestRetryHandler retryHandler; //重试机制 + + private static CloseableHttpClient httpClient=null; + + public static int getMaxTimeout() { + return MAX_TIMEOUT; + } + + public static void setMaxTimeout(int maxTimeout) { + MAX_TIMEOUT = maxTimeout; + } + + public static int getMaxTotal() { + return MAX_TOTAL; + } + + public static void setMaxTotal(int maxTotal) { + MAX_TOTAL = maxTotal; + } + + public static int getRouteMaxTotal() { + return ROUTE_MAX_TOTAL; + } + + public static void setRouteMaxTotal(int routeMaxTotal) { + ROUTE_MAX_TOTAL = routeMaxTotal; + } + + public static int getMaxRetry() { + return MAX_RETRY; + } + + public static void setMaxRetry(int maxRetry) { + MAX_RETRY = maxRetry; + } + + public static boolean isSslVerify() { + return SSL_VERIFY; + } + + public static void setSslVerify(boolean sslVerify) { + SSL_VERIFY = sslVerify; + } + + public static String getProxyIp() { + return PROXY_IP; + } + + public static void setProxyIp(String proxyIp) { + PROXY_IP = proxyIp; + } + + public static int getProxyPort() { + return PROXY_PORT; + } + + public static void setProxyPort(int proxyPort) { + PROXY_PORT = proxyPort; + } + + public static String getProxyAgreement() { + return PROXY_AGREEMENT; + } + + public static void setProxyAgreement(String proxyAgreement) { + PROXY_AGREEMENT = proxyAgreement; + } + + public static boolean getOpenProxy() { + return OPEN_PROXY; + } + + public static void setOpenProxy(boolean openProxy) { + OPEN_PROXY = openProxy; + } + + public static String getProxyUsername() { + return PROXY_USERNAME; + } + + public static void setProxyUserame(String proxyUsername) { + PROXY_USERNAME = proxyUsername; + } + + public static String getProxyPassword() { + return PROXY_PASSWORD; + } + + public static void setProxyPassword(String proxyPassword) { + PROXY_PASSWORD = proxyPassword; + } + + + + + /** + * 不允许外部创建实例 + */ + private EsignHttpCfgHelper() { + } + + //------------------------------公有方法start-------------------------------------------- + + + /** + * @description 发起HTTP / HTTPS 请求 + * + * @param reqType + * {@link EsignRequestType} 请求类型 GET、 POST 、 DELETE 、 PUT + * @param httpUrl + * {@link String} 请求目标地址 + * @param headers + * {@link Map} 请求头 + * @param param + * {@link Object} 参数 + * @return + * @throws EsignDemoException + * @author 澄泓 + */ + public static EsignHttpResponse sendHttp(EsignRequestType reqType, String httpUrl, Map headers, Object param, boolean debug) + throws EsignDemoException { + HttpRequestBase reqBase=null; + if(httpUrl.startsWith("http")){ + reqBase=reqType.getHttpType(httpUrl); + }else{ + throw new EsignDemoException("请求url地址格式错误"); + } + if(debug){ + LOGGER.info("请求头:{}",headers+"\n"); + LOGGER.info("请求参数\n{}", param+"\n"); + LOGGER.info("请求地址\n:{}\n请求方式\n:{}",reqBase.getURI(),reqType+"\n"); + } + //请求方法不是GET或者DELETE时传入body体,否则不传入。 + String[] methods = {"DELETE", "GET"}; + if(param instanceof String&&Arrays.binarySearch(methods, reqType.name())<0){//POST或者PUT请求 + ((HttpEntityEnclosingRequest) reqBase).setEntity( + new StringEntity(String.valueOf(param), ContentType.create("application/json", "UTF-8"))); + } + //参数时字节流数组 + else if(param instanceof byte[]) { + reqBase=reqType.getHttpType(httpUrl); + byte[] paramBytes = (byte[])param; + ((HttpEntityEnclosingRequest) reqBase).setEntity(new ByteArrayEntity(paramBytes)); + } + //参数是form表单时 + else if(param instanceof List){ + ((HttpEntityEnclosingRequest) reqBase).setEntity(new UrlEncodedFormEntity((Iterable) param)); + } + httpClient = getHttpClient(); + config(reqBase); + + //设置请求头 + if(headers != null &&headers.size()>0) { + for(Map.Entry entry :headers.entrySet()) { + reqBase.setHeader(entry.getKey(), entry.getValue()); + } + } + //响应对象 + CloseableHttpResponse res = null; + //响应内容 + String resCtx = null; + int status; + EsignHttpResponse esignHttpResponse = new EsignHttpResponse(); + try { + //执行请求 + res = httpClient.execute(reqBase); + status=res.getStatusLine().getStatusCode(); + + //获取请求响应对象和响应entity + HttpEntity httpEntity = res.getEntity(); + if(httpEntity != null) { + resCtx = EntityUtils.toString(httpEntity,"utf-8"); + } + if(debug) { + LOGGER.info("响应\n{}", resCtx + "\n"); + LOGGER.info("----------------------------end------------------------"); + } + } catch (NoHttpResponseException e) { + throw new EsignDemoException("服务器丢失了",e); + } catch (SSLHandshakeException e){ + String msg = MessageFormat.format("SSL握手异常", e); + EsignDemoException ex = new EsignDemoException(msg, e); + throw ex; + } catch (UnknownHostException e){ + EsignDemoException ex = new EsignDemoException("服务器找不到", e); + ex.initCause(e); + throw ex; + } catch(ConnectTimeoutException e){ + EsignDemoException ex = new EsignDemoException("连接超时", e); + ex.initCause(e); + throw ex; + } catch(SSLException e){ + EsignDemoException ex = new EsignDemoException("SSL异常",e); + ex.initCause(e); + throw ex; + } catch (ClientProtocolException e) { + EsignDemoException ex = new EsignDemoException("请求头异常",e); + ex.initCause(e); + throw ex; + } catch (IOException e) { + EsignDemoException ex = new EsignDemoException("网络请求失败",e); + ex.initCause(e); + throw ex; + } finally { + if(res != null) { + try { + res.close(); + } catch (IOException e) { + EsignDemoException ex = new EsignDemoException("--->>关闭请求响应失败",e); + ex.initCause(e); + throw ex; + } + } + } + esignHttpResponse.setStatus(status); + esignHttpResponse.setBody(resCtx); + return esignHttpResponse; + } + //------------------------------公有方法end---------------------------------------------- + + //------------------------------私有方法start-------------------------------------------- + + /** + * @description 请求头和超时时间配置 + * + * @param httpReqBase + * @author 澄泓 + */ + private static void config(HttpRequestBase httpReqBase) { + // 配置请求的超时设置 + RequestConfig.Builder builder = RequestConfig.custom() + .setConnectionRequestTimeout(MAX_TIMEOUT) + .setConnectTimeout(MAX_TIMEOUT) + .setSocketTimeout(MAX_TIMEOUT); + if(OPEN_PROXY){ + HttpHost proxy=new HttpHost(PROXY_IP,PROXY_PORT,PROXY_AGREEMENT); + builder.setProxy(proxy); + } + RequestConfig requestConfig = builder.build(); + httpReqBase.setConfig(requestConfig); + } + + /** + * @description 连接池配置 + * + * @return + * @author 澄泓 + */ + private static void cfgPoolMgr() throws EsignDemoException { + ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); + LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory(); + if(!SSL_VERIFY){ + sslsf=sslConnectionSocketFactory(); + } + + Registry registry = RegistryBuilder.create() + .register("http", plainsf) + .register("https", sslsf) + .build(); + + //连接池管理器 + connMgr = new PoolingHttpClientConnectionManager(registry); + //请求池最大连接数 + connMgr.setMaxTotal(MAX_TOTAL); + //但域名最大的连接数 + connMgr.setDefaultMaxPerRoute(ROUTE_MAX_TOTAL); + } + + + + + /** + * @description 设置重试机制 + * + * @author 澄泓 + */ + private static void cfgRetryHandler() { + retryHandler = new HttpRequestRetryHandler() { + + @Override + public boolean retryRequest(IOException e, int excCount, HttpContext ctx) { + //超过最大重试次数,就放弃 + if(excCount > MAX_RETRY) { + return false; + } + //服务器丢掉了链接,就重试 + if(e instanceof NoHttpResponseException) { + return true; + } + //不重试SSL握手异常 + if(e instanceof SSLHandshakeException) { + return false; + } + //中断 + if(e instanceof InterruptedIOException) { + return false; + } + //目标服务器不可达 + if(e instanceof UnknownHostException) { + return false; + } + //连接超时 + //SSL异常 + if(e instanceof SSLException) { + return false; + } + + HttpClientContext clientCtx = HttpClientContext.adapt(ctx); + HttpRequest req = clientCtx.getRequest(); + //如果是幂等请求,就再次尝试 + if(!(req instanceof HttpEntityEnclosingRequest)) { + return true; + } + return false; + } + }; + } + + /** + * 忽略域名校验 + */ + private static SSLConnectionSocketFactory sslConnectionSocketFactory() throws EsignDemoException { + try { + SSLContext ctx = SSLContext.getInstance("TLS"); // 创建一个上下文(此处指定的协议类型似乎不是重点) + X509TrustManager tm = new X509TrustManager() { // 创建一个跳过SSL证书的策略 + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { + } + + public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { + } + }; + ctx.init(null, new TrustManager[] { tm }, null); // 使用上面的策略初始化上下文 + return new SSLConnectionSocketFactory(ctx, new String[] { "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" }, null, NoopHostnameVerifier.INSTANCE); + }catch (Exception e){ + EsignDemoException ex = new EsignDemoException("忽略域名校验失败",e); + ex.initCause(e); + throw ex; + } + + } + + /** + * @description 获取单例HttpClient + * + * @return + * @author 澄泓 + */ + private static synchronized CloseableHttpClient getHttpClient() throws EsignDemoException { + if(httpClient==null) { + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials(new AuthScope(PROXY_IP,PROXY_PORT),new UsernamePasswordCredentials(PROXY_USERNAME, PROXY_PASSWORD)); + cfgPoolMgr(); + cfgRetryHandler(); + HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); + httpClient = httpClientBuilder.setDefaultCredentialsProvider(credsProvider).setConnectionManager(connMgr).setRetryHandler(retryHandler).build(); + } + return httpClient; + + } + //------------------------------私有方法end---------------------------------------------- + + +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/constant/FileTransformation.java b/ruoyi-common/src/main/java/com/ruoyi/common/constant/FileTransformation.java new file mode 100644 index 0000000..f63a3d9 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/constant/FileTransformation.java @@ -0,0 +1,284 @@ +/* + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.ruoyi.common.constant; + +import com.ruoyi.common.exception.EsignDemoException; +import org.apache.commons.codec.binary.Base64; + +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.Map; + +/** + * @author 澄泓 + * @version JDK1.7 + * @description 文件转换类 + * @date 2020/10/26 10:47 + */ +public class FileTransformation { + + /** + * 传入本地文件路径转二进制byte + * + * @param srcFilePath 本地文件路径 + * @return + * @throws EsignDemoException + */ + public static byte[] fileToBytes(String srcFilePath) throws EsignDemoException { + return getBytes(srcFilePath); + } + + /** + * 图片转base64 + * + * @param filePath 本地文件路径 + * @return + * @throws EsignDemoException + */ + public static String fileToBase64(String filePath) throws EsignDemoException { + byte[] bytes; + String base64 = null; + bytes = fileToBytes(filePath); + base64 = Base64.encodeBase64String(bytes); + base64 = base64.replaceAll("\r\n", ""); + return base64; + } + + public static void main(String[] args) throws EsignDemoException { + System.out.println(getFileContentMD5("D:\\文档\\PLT2022-02124CT.pdf")); + } + + /*** + * 计算文件内容的Content-MD5 + * @param filePath 文件路径 + * @return + */ + public static String getFileContentMD5(String filePath) throws EsignDemoException { + // 获取文件MD5的二进制数组(128位) + byte[] bytes = getFileMD5Bytes128(filePath); + // 对文件MD5的二进制数组进行base64编码 + return new String(Base64.encodeBase64String(bytes)); + } + + /** + * 下载文件 + * + * @param httpUrl 网络文件地址url + * @return + */ + public static boolean downLoadFileByUrl(String httpUrl, String dir) throws EsignDemoException { + InputStream fis = null; + FileOutputStream fileOutputStream = null; + try { + URL url = new URL(httpUrl); + HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); + httpConn.connect(); + fis = httpConn.getInputStream(); + fileOutputStream = new FileOutputStream(new File(dir)); + byte[] md5Bytes = null; + + byte[] buffer = new byte[1024]; + int length = -1; + while ((length = fis.read(buffer, 0, 1024)) != -1) { + fileOutputStream.write(buffer, 0, length); + } + } catch (IOException e) { + EsignDemoException ex = new EsignDemoException("获取文件流异常", e); + ex.initCause(e); + throw ex; + } finally { + try { + if (fis != null) { + fis.close(); + } + if (fileOutputStream != null) { + fileOutputStream.close(); + } + } catch (IOException e) { + EsignDemoException ex = new EsignDemoException("关闭文件流异常", e); + ex.initCause(e); + throw ex; + } + } + return true; + } + + + /** + * 网络文件转二进制MD5数组并获取文件大小 + * + * @param fileUrl 网络文件地址url + * @return + */ + public static Map fileUrlToBytes(String fileUrl) throws EsignDemoException { + HashMap map = new HashMap(); + try { + URL url = new URL(fileUrl); + HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); + httpConn.connect(); + InputStream fis = httpConn.getInputStream(); + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + outStream.close(); + map.put("fileSize", fis.available()); + byte[] md5Bytes = null; + MessageDigest md5 = MessageDigest.getInstance("MD5"); + byte[] buffer = new byte[1024]; + int length = -1; + while ((length = fis.read(buffer, 0, 1024)) != -1) { + md5.update(buffer, 0, length); + outStream.write(buffer, 0, length); + } + md5Bytes = md5.digest(); + byte[] fileData = outStream.toByteArray(); + map.put("fileData", fileData); + outStream.close(); + fis.close(); + map.put("md5Bytes", md5Bytes); + } catch (IOException e) { + EsignDemoException ex = new EsignDemoException("获取文件流异常", e); + ex.initCause(e); + throw ex; + } catch (NoSuchAlgorithmException e) { + EsignDemoException ex = new EsignDemoException("文件计算异常", e); + ex.initCause(e); + throw ex; + } + return map; + } + + /*** + * 获取文件MD5的二进制数组(128位) + * @param filePath + * @return + * @throws EsignDemoException + */ + public static byte[] getFileMD5Bytes128(String filePath) throws EsignDemoException { + FileInputStream fis = null; + byte[] md5Bytes = null; + try { + File file = new File(filePath); + fis = new FileInputStream(file); + MessageDigest md5 = MessageDigest.getInstance("MD5"); + byte[] buffer = new byte[1024]; + int length = -1; + while ((length = fis.read(buffer, 0, 1024)) != -1) { + md5.update(buffer, 0, length); + } + md5Bytes = md5.digest(); + fis.close(); + } catch (FileNotFoundException e) { + EsignDemoException ex = new EsignDemoException("文件找不到", e); + ex.initCause(e); + throw ex; + } catch (NoSuchAlgorithmException e) { + EsignDemoException ex = new EsignDemoException("不支持此算法", e); + ex.initCause(e); + throw ex; + } catch (IOException e) { + EsignDemoException ex = new EsignDemoException("输入流或输出流异常", e); + ex.initCause(e); + throw ex; + } finally { + if (fis != null) { + try { + fis.close(); + } catch (IOException e) { + EsignDemoException ex = new EsignDemoException("关闭文件输入流失败", e); + ex.initCause(e); + throw ex; + } + } + } + return md5Bytes; + } + + /** + * @param path + * @return + * @throws EsignDemoException + * @description 根据文件路径,获取文件base64 + * @author 宫清 + * @date 2019年7月21日 下午4:22:08 + */ + public static String getBase64Str(String path) throws EsignDemoException { + InputStream is = null; + try { + is = new FileInputStream(new File(path)); + byte[] bytes = new byte[is.available()]; + is.read(bytes); + return Base64.encodeBase64String(bytes); + } catch (Exception e) { + EsignDemoException ex = new EsignDemoException("获取文件输入流失败", e); + ex.initCause(e); + throw ex; + } finally { + if (is != null) { + try { + is.close(); + } catch (IOException e) { + EsignDemoException ex = new EsignDemoException("关闭文件输入流失败", e); + ex.initCause(e); + throw ex; + } + } + } + } + + /** + * @param path 文件路径 + * @return + * @description 获取文件名称 + * @author 宫清 + * @date 2019年7月21日 下午8:21:16 + */ + public static String getFileName(String path) { + return new File(path).getName(); + } + + /** + * @param filePath {@link String} 文件地址 + * @return + * @throws EsignDemoException + * @description 获取文件字节流 + * @date 2019年7月10日 上午9:17:00 + * @author 宫清 + */ + public static byte[] getBytes(String filePath) throws EsignDemoException { + File file = new File(filePath); + FileInputStream fis = null; + byte[] buffer = null; + try { + fis = new FileInputStream(file); + buffer = new byte[(int) file.length()]; + fis.read(buffer); + } catch (Exception e) { + EsignDemoException ex = new EsignDemoException("获取文件字节流失败", e); + ex.initCause(e); + throw ex; + } finally { + if (fis != null) { + try { + fis.close(); + } catch (IOException e) { + EsignDemoException ex = new EsignDemoException("关闭文件字节流失败", e); + ex.initCause(e); + throw ex; + } + } + } + return buffer; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/EsignCoreSdkInfo.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/EsignCoreSdkInfo.java new file mode 100644 index 0000000..d97603d --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/EsignCoreSdkInfo.java @@ -0,0 +1,24 @@ +package com.ruoyi.common.core.domain.entity; +/** + * esignSDK-core信息类 + * @author 澄泓 + * @date 2022/2/22 13:59 + * @version + */ +public class EsignCoreSdkInfo { + private static final String SdkVersion="Esign-Sdk-Core1.0"; + private static final String SupportedVersion="JDK1.7 MORE THAN"; + + private static final String Info="sdk-esign-api核心工具包,主要处理e签宝公有云产品接口调用时的签名计算以及网络请求,通过EsignHttpHelper.signAndBuildSignAndJsonHeader构造签名鉴权+json数据格式的请求头,通过HttpHelper.doCommHttp方法入参发起网络请求。让开发者无需关注具体的请求签名算法,专注于接口业务的json参数构造"; + public static String getSdkVersion() { + return SdkVersion; + } + + public static String getInfo() { + return Info; + } + + public static String getSupportedVersion() { + return SupportedVersion; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/EsignHttpResponse.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/EsignHttpResponse.java new file mode 100644 index 0000000..26375c0 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/EsignHttpResponse.java @@ -0,0 +1,24 @@ +package com.ruoyi.common.core.domain.entity; +/** + * 网络请求的response类 + */ +public class EsignHttpResponse { + private int status; + private String body; + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/enums/EsignRequestType.java b/ruoyi-common/src/main/java/com/ruoyi/common/enums/EsignRequestType.java new file mode 100644 index 0000000..8b87de6 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/enums/EsignRequestType.java @@ -0,0 +1,39 @@ +package com.ruoyi.common.enums; + +import org.apache.http.client.methods.*; + +/** + * @description 请求类型 + * @author 澄泓 + * @since JDK1.7 + */ +public enum EsignRequestType { + + POST{ + @Override + public HttpRequestBase getHttpType(String url) { + return new HttpPost(url); + } + }, + GET{ + @Override + public HttpRequestBase getHttpType(String url) { + return new HttpGet(url); + } + }, + DELETE{ + @Override + public HttpRequestBase getHttpType(String url) { + return new HttpDelete(url); + } + }, + PUT{ + @Override + public HttpRequestBase getHttpType(String url) { + return new HttpPut(url); + } + }, + ; + + public abstract HttpRequestBase getHttpType(String url); +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/exception/EsignDemoException.java b/ruoyi-common/src/main/java/com/ruoyi/common/exception/EsignDemoException.java new file mode 100644 index 0000000..7be2957 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/exception/EsignDemoException.java @@ -0,0 +1,36 @@ +package com.ruoyi.common.exception; + +/** + * description 自定义全局异常 + * @author 澄泓 + * datetime 2019年7月1日上午10:43:24 + */ +public class EsignDemoException extends Exception { + + private static final long serialVersionUID = 4359180081622082792L; + private Exception e; + + public EsignDemoException(String msg) { + super(msg); + } + + public EsignDemoException(String msg, Throwable cause) { + super(msg,cause); + } + + public EsignDemoException(){ + + } + + public Exception getE() { + return e; + } + + public void setE(Exception e) { + this.e = e; + } + + + + +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/EsignHttpHelper.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/EsignHttpHelper.java new file mode 100644 index 0000000..ed255e5 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/EsignHttpHelper.java @@ -0,0 +1,178 @@ +package com.ruoyi.common.utils; + + +import com.ruoyi.common.constant.EsignEncryption; +import com.ruoyi.common.constant.EsignHeaderConstant; +import com.ruoyi.common.constant.EsignHttpCfgHelper; +import com.ruoyi.common.core.domain.entity.EsignCoreSdkInfo; +import com.ruoyi.common.core.domain.entity.EsignHttpResponse; +import com.ruoyi.common.enums.EsignRequestType; +import com.ruoyi.common.exception.EsignDemoException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description Http 请求 辅助类 + * @author 澄泓 + * @since JDK1.7 + */ +public class EsignHttpHelper { + private static final Logger LOGGER = LoggerFactory.getLogger(EsignHttpHelper.class); + + /** + * 不允许外部创建实例 + */ + private EsignHttpHelper() { + + } + + /** + * @description 发送常规HTTP 请求 + * + * @param reqType 请求方式 + * @param url 请求路径 + * @param paramStr 请求参数 + * @return + * @throws EsignDemoException + * @author 澄泓 + */ + public static EsignHttpResponse doCommHttp(String host, String url, EsignRequestType reqType, Object paramStr , Map httpHeader, boolean debug) throws EsignDemoException { + + return EsignHttpCfgHelper.sendHttp(reqType, host+url,httpHeader, paramStr, debug); + + } + + + /** + * @description 发送文件流上传 HTTP 请求 + * + * @param reqType 请求方式 + * @param uploadUrl 请求路径 + * @param param 请求参数 + * @param fileContentMd5 文件fileContentMd5 + * @param contentType 文件MIME类型 + * @return + * @throws EsignDemoException + * @author 澄泓 + */ + public static EsignHttpResponse doUploadHttp( String uploadUrl,EsignRequestType reqType,byte[] param, String fileContentMd5, + String contentType, boolean debug) throws EsignDemoException { + Map uploadHeader = buildUploadHeader(fileContentMd5, contentType); + if(debug){ + LOGGER.info("----------------------------start------------------------"); + LOGGER.info("fileContentMd5:{}",fileContentMd5); + LOGGER.info("contentType:{}",contentType); + } + return EsignHttpCfgHelper.sendHttp(reqType,uploadUrl, uploadHeader, param,debug); + } + + + + /** + * @description 构建一个签名鉴权+json数据的esign请求头 + * @return + * @author 澄泓 + */ + public static Map buildSignAndJsonHeader(String projectId,String contentMD5,String accept,String contentType,String authMode) { + + Map header = new HashMap<>(); + header.put("X-Tsign-Open-App-Id", projectId); + header.put("X-Tsign-Open-Version-Sdk",EsignCoreSdkInfo.getSdkVersion()); + header.put("X-Tsign-Open-Ca-Timestamp", EsignEncryption.timeStamp()); + header.put("Accept",accept); + header.put("Content-MD5",contentMD5); + header.put("Content-Type", contentType); + header.put("X-Tsign-Open-Auth-Mode", authMode); + return header; + } + + /** + * 签名计算并且构建一个签名鉴权+json数据的esign请求头 + * @param httpMethod + * * The name of a supported {@linkplain java.nio.charset.Charset + * * charset} + * @return + */ + public static Map signAndBuildSignAndJsonHeader(String projectId, String secret,String paramStr,String httpMethod,String url,boolean debug) throws EsignDemoException { + String contentMD5=""; + //统一转大写处理 + httpMethod = httpMethod.toUpperCase(); + if("GET".equals(httpMethod)||"DELETE".equals(httpMethod)){ + paramStr=null; + contentMD5=""; + } else if("PUT".equals(httpMethod)||"POST".equals(httpMethod)){ + //对body体做md5摘要 + contentMD5= EsignEncryption.doContentMD5(paramStr); + }else{ + throw new EsignDemoException(String.format("不支持的请求方法%s",httpMethod)); + } + //构造一个初步的请求头 + Map esignHeaderMap = buildSignAndJsonHeader(projectId, contentMD5, EsignHeaderConstant.ACCEPT.VALUE(), EsignHeaderConstant.CONTENTTYPE_JSON.VALUE(), EsignHeaderConstant.AUTHMODE.VALUE()); + //排序 + url=EsignEncryption.sortApiUrl(url); + //传入生成的bodyMd5,加上其他请求头部信息拼接成字符串 + String message = EsignEncryption.appendSignDataString(httpMethod, esignHeaderMap.get("Content-MD5"),esignHeaderMap.get("Accept"),esignHeaderMap.get("Content-Type"),esignHeaderMap.get("Headers"),esignHeaderMap.get("Date"), url); + //整体做sha256签名 + String reqSignature = EsignEncryption.doSignatureBase64(message, secret); + //请求头添加签名值 + esignHeaderMap.put("X-Tsign-Open-Ca-Signature",reqSignature); + if(debug){ + LOGGER.info("----------------------------start------------------------"); + LOGGER.info("待计算body值:{}", paramStr+"\n"); + LOGGER.info("MD5值:{}",contentMD5+"\n"); + LOGGER.info("待签名字符串:{}",message+"\n"); + LOGGER.info("签名值:{}",reqSignature+"\n"); + } + return esignHeaderMap; + } + + + /** + * @description 构建一个Token鉴权+jsons数据的esign请求头 + * @return + * @author 澄泓 + */ + public static Map buildTokenAndJsonHeader(String appid,String token) { + Map esignHeader = new HashMap<>(); + esignHeader.put("X-Tsign-Open-Version-Sdk", EsignCoreSdkInfo.getSdkVersion()); + esignHeader.put("Content-Type", EsignHeaderConstant.CONTENTTYPE_JSON.VALUE()); + esignHeader.put("X-Tsign-Open-App-Id", appid); + esignHeader.put("X-Tsign-Open-Token", token); + return esignHeader; + } + + /** + * @description 构建一个form表单数据的esign请求头 + * @return + * @author 澄泓 + */ + public static Map buildFormDataHeader(String appid) { + Map esignHeader = new HashMap<>(); + esignHeader.put("X-Tsign-Open-Version-Sdk",EsignCoreSdkInfo.getSdkVersion()); + esignHeader.put("X-Tsign-Open-Authorization-Version","v2"); + esignHeader.put("Content-Type", EsignHeaderConstant.CONTENTTYPE_FORMDATA.VALUE()); + esignHeader.put("X-Tsign-Open-App-Id", appid); + return esignHeader; + } + + /** + * @description 创建文件流上传 请求头 + * + * @param fileContentMd5 + * @param contentType + * @return + * @author 澄泓 + */ + public static Map buildUploadHeader(String fileContentMd5, String contentType) { + Map header = new HashMap<>(); + header.put("Content-MD5", fileContentMd5); + header.put("Content-Type", contentType); + + return header; + } + + // ------------------------------私有方法end---------------------------------------------- +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/bean/EsignFileBean.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/bean/EsignFileBean.java new file mode 100644 index 0000000..5f46713 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/bean/EsignFileBean.java @@ -0,0 +1,57 @@ +package com.ruoyi.common.utils.bean; + + +import com.ruoyi.common.constant.FileTransformation; +import com.ruoyi.common.exception.EsignDemoException; + +import java.io.File; + +/** + * @description 文件基础信息封装类 + * @author 澄泓 + * @date 2020/10/26 14:54 + * @version JDK1.7 + */ +public class EsignFileBean { + //文件名称 + private String fileName; + //文件大小 + private int fileSize; + //文件内容MD5 + private String fileContentMD5; + //文件地址 + private String filePath; + + + public EsignFileBean(String filePath) throws EsignDemoException { + this.filePath=filePath; + this.fileContentMD5 = FileTransformation.getFileContentMD5(filePath); + File file = new File(filePath); + if (!file.exists()) { + throw new EsignDemoException("文件不存在"); + } + this.fileName = file.getName(); + this.fileSize = (int) file.length(); + } + + public String getFileName() { + return fileName; + } + + public int getFileSize() { + return fileSize; + } + + public String getFileContentMD5() { + return fileContentMD5; + } + + /** + * 传入本地文件地址获取二进制数据 + * @return + * @throws EsignDemoException + */ + public byte[] getFileBytes() throws EsignDemoException { + return FileTransformation.fileToBytes(filePath); + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/SaaSAPIFileUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/SaaSAPIFileUtils.java new file mode 100644 index 0000000..5ea9410 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/SaaSAPIFileUtils.java @@ -0,0 +1,43 @@ +package com.ruoyi.common.utils.file; + +import com.ruoyi.common.config.EsignDemoConfig; +import com.ruoyi.common.constant.EsignHeaderConstant; +import com.ruoyi.common.core.domain.entity.EsignHttpResponse; +import com.ruoyi.common.enums.EsignRequestType; +import com.ruoyi.common.exception.EsignDemoException; +import com.ruoyi.common.utils.EsignHttpHelper; +import com.ruoyi.common.utils.bean.EsignFileBean; + +import java.util.Map; + +public class SaaSAPIFileUtils { + private static String eSignHost= EsignDemoConfig.EsignHost; + private static String eSignAppId= EsignDemoConfig.EsignAppId; + private static String eSignAppSecret=EsignDemoConfig.EsignAppSecret; + /** + * 获取文件上传地址 + * + * @return + */ + public static EsignHttpResponse getUploadUrl(String filePath) throws EsignDemoException { + //自定义的文件封装类,传入文件地址可以获取文件的名称大小,文件流等数据 + EsignFileBean esignFileBean = new EsignFileBean(filePath); + String apiaddr = "/v3/files/file-upload-url"; + //请求参数body体,json格式。get或者delete请求时jsonString传空json:"{}"或者null + String jsonParm = "{\n" + + " \"contentMd5\": \"" + esignFileBean.getFileContentMD5() + "\",\n" + + " \"fileName\":\"" + esignFileBean.getFileName() + "\"," + + " \"fileSize\": " + esignFileBean.getFileSize() + ",\n" + + " \"convertToPDF\":" +true+ ",\n" + + " \"contentType\": \"" + EsignHeaderConstant.CONTENTTYPE_STREAM.VALUE() + "\"\n" + + "}"; + //请求方法 + EsignRequestType requestType = EsignRequestType.POST; + //生成签名鉴权方式的的header + Map header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId, eSignAppSecret, jsonParm, requestType.name(), apiaddr, true); + //发起接口请求 + return EsignHttpHelper.doCommHttp(eSignHost, apiaddr, requestType, jsonParm, header, true); + } + + +}