安眼大屏公网访问获取token接口对接

This commit is contained in:
feng
2025-09-28 17:25:07 +08:00
parent 19e46db6a1
commit 2b6e5d2736
12 changed files with 460 additions and 28 deletions
@@ -104,4 +104,10 @@ public interface AnYanClient {
* @return
*/
IPage<MedicalAbnormalVO> medicalAbnormalList(MedicalAbnormalDTO param);
/**
* 公网环境获取服务访问token (目前仅用于访问安眼大屏)
* @return
*/
String publicNetworkToken() throws Exception;
}
@@ -4,6 +4,7 @@ import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.renkang.anyan.config.AnYanProperties;
@@ -16,10 +17,10 @@ import com.renkang.anyan.model.dto.HealthSignListParam;
import com.renkang.anyan.model.dto.MedicalAbnormalDTO;
import com.renkang.anyan.model.vo.*;
import com.renkang.anyan.utils.PageResultToBeanUtil;
import com.renkang.anyan.utils.SM4Utils;
import com.renkang.anyan.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.ExceptionAssertsUtil;
import org.jeecg.util.RedisClientUtil;
import org.jeecg.util.RedisKeyPrefix;
@@ -28,10 +29,12 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
/**
@@ -44,13 +47,15 @@ import java.util.stream.Collectors;
@EnableRetry
@RequiredArgsConstructor
public class AnYanClientExecutor implements AnYanClient {
//安眼获取token访问公钥
private String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJL0JkqsUoK6kt3JyogsgqNp9VDGDp+t3ZAGMbVoMPdHNT2nfiIVh9ZMNHF7g2XiAa8O8AQWyh2PjMR0NiUSVQMCAwEAAQ==";
private final RedisClientUtil redisClientUtil;
private final AnYanProperties anYanProperties;
@Override
public String getAuthToken() {
String token = redisClientUtil.get(new RedisKeyPrefix(AnYanConstants.AN_YAN_API_TOKEN_PREFIX) ,"token",String.class);
if(StringUtils.isEmpty(token)){
if(StrUtil.isEmpty(token)){
AuthResult authResult = getAuthTokenExecutor();
if(ObjectUtil.isNotEmpty(authResult) && StrUtil.isNotEmpty(authResult.getAccess_token())){
token = authResult.getAccess_token();
@@ -92,75 +97,119 @@ public class AnYanClientExecutor implements AnYanClient {
}
@Override
@Retryable(maxAttempts = 2)
public List<MedicalPeopleNumStatisticsVO> examinationStatistics(Integer medicalYear) {
if(null == medicalYear){ medicalYear = DateUtil.year(new Date()); }
JSONObject param = new JSONObject();
param.put("medicalYear",String.valueOf(medicalYear));
Result<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.HEALTH_EXAMINATION_STATISTICS, buildTokenHeader(), param);
List<Object> listMaps = (List<Object>) result.getResult();
AnYanResult<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.HEALTH_EXAMINATION_STATISTICS, buildTokenHeader(), param);
List<Object> listMaps = (List<Object>) result.getData();
return listMaps.stream().map(lMap -> BeanUtil.toBean(lMap, MedicalPeopleNumStatisticsVO.class)).collect(Collectors.toList());
}
@Override
@Retryable(maxAttempts = 2)
public HealthSignStatVO healthCheckStatistics(Date beginDate, Date endDate) {
JSONObject param = new JSONObject();
param.put("inputDateBegin",ObjectUtil.isEmpty(beginDate)? DateUtil.today() : DateUtil.formatDate(beginDate));
param.put("inputDateEnd",ObjectUtil.isEmpty(endDate)? DateUtil.today() : DateUtil.formatDate(endDate));
Result<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.HEALTH_CHECK_STATISTICS, buildTokenHeader(), param);
return BeanUtil.toBean(result.getResult(),HealthSignStatVO.class);
AnYanResult<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.HEALTH_CHECK_STATISTICS, buildTokenHeader(), param);
return BeanUtil.toBean(result.getData(),HealthSignStatVO.class);
}
@Override
@Retryable(maxAttempts = 2)
public IPage<BloodPressureList> bloodPressureList(HealthSignListParam healthSignListParam) {
Result<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.BLOOD_PRESSURE_LIST, buildTokenHeader(), healthSignListParam);
AnYanResult<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.BLOOD_PRESSURE_LIST, buildTokenHeader(), healthSignListParam);
return new PageResultToBeanUtil<BloodPressureList>().transform(result,BloodPressureList.class);
}
@Override
@Retryable(maxAttempts = 2)
public IPage<WeightPressureList> weightPressureList(HealthSignListParam healthSignListParam) {
Result<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.WEIGHT_PRESSURE_LIST, buildTokenHeader(), healthSignListParam);
AnYanResult<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.WEIGHT_PRESSURE_LIST, buildTokenHeader(), healthSignListParam);
return new PageResultToBeanUtil<WeightPressureList>().transform(result,WeightPressureList.class);
}
@Override
@Retryable(maxAttempts = 2)
public IPage<BloodSugarClockSList> bloodSugarClockSList(HealthSignListParam healthSignListParam) {
Result<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.BLOOD_SUGAR_CLOCKS_LIST, buildTokenHeader(), healthSignListParam);
AnYanResult<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.BLOOD_SUGAR_CLOCKS_LIST, buildTokenHeader(), healthSignListParam);
return new PageResultToBeanUtil<BloodSugarClockSList>().transform(result,BloodSugarClockSList.class);
}
@Override
@Retryable(maxAttempts = 2)
public List<HospitalListVO> hospitalList() {
Result<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.HOSPITAL_LIST, buildTokenHeader(), null);
List<Object> listMaps = (List<Object>) result.getResult();
AnYanResult<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.HOSPITAL_LIST, buildTokenHeader(), null);
List<Object> listMaps = (List<Object>) result.getData();
return listMaps.stream().map(lMap -> BeanUtil.toBean(lMap, HospitalListVO.class)).collect(Collectors.toList());
}
@Override
@Retryable(maxAttempts = 2)
public List<HealthRoomBaseVO> healthPlaceHomList() {
Result<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.HEALTH_PLACE_ROOM_LIST, buildTokenHeader(),null);
List<Object> listMaps = (List<Object>) result.getResult();
AnYanResult<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.HEALTH_PLACE_ROOM_LIST, buildTokenHeader(),null);
List<Object> listMaps = (List<Object>) result.getData();
return listMaps.stream().map(lMap -> BeanUtil.toBean(lMap, HealthRoomBaseVO.class)).collect(Collectors.toList());
}
@Override
@Retryable(maxAttempts = 2)
public IPage<HealthPlaceHomDetailsVO> healthPlaceHomDetailList(HealthRoomDTO healthRoomDTO) {
Result<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.HEALTH_PLACE_ROOM_INFO_LIST, buildTokenHeader(), healthRoomDTO);
AnYanResult<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.HEALTH_PLACE_ROOM_INFO_LIST, buildTokenHeader(), healthRoomDTO);
return new PageResultToBeanUtil<HealthPlaceHomDetailsVO>().transform(result,HealthPlaceHomDetailsVO.class);
}
@Override
@Retryable(maxAttempts = 2)
public MedicalAbnormalStatisticsVO medicalAbnormalStatistics(Integer medicalYear) {
if(null == medicalYear){ medicalYear = DateUtil.year(new Date()); }
JSONObject param = new JSONObject();
param.put("medicalYear",medicalYear);
Result<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.MEDICAL_ABNORMAL_STATISTICS, buildTokenHeader(), param);
return BeanUtil.toBean(result.getResult(),MedicalAbnormalStatisticsVO.class);
AnYanResult<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.MEDICAL_ABNORMAL_STATISTICS, buildTokenHeader(), param);
return BeanUtil.toBean(result.getData(),MedicalAbnormalStatisticsVO.class);
}
@Override
@Retryable(maxAttempts = 2)
public IPage<MedicalAbnormalVO> medicalAbnormalList(MedicalAbnormalDTO param) {
Result<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.MEDICAL_ABNORMAL_LIST, buildTokenHeader(), param);
AnYanResult<Object> result = RestTemplateUtil.postExchange(AnYanApiEnum.MEDICAL_ABNORMAL_LIST, buildTokenHeader(), param);
return new PageResultToBeanUtil<MedicalAbnormalVO>().transform(result,MedicalAbnormalVO.class);
}
@Override
public String publicNetworkToken() throws Exception {
String token = redisClientUtil.get(new RedisKeyPrefix(AnYanConstants.AN_YAN_API_TOKEN_PREFIX) ,"publicToken",String.class);
if(StrUtil.isEmpty(token)){
JSONObject param = new JSONObject();
String password = anYanProperties.getPublicPassWrod();
String userName = anYanProperties.getPublicUserNmae();
String sm4Password = SM4Utils.encryptSM4(password);
String encryptPassword = StringUtils.encryptByPublicKey(publicKey, password);
param.put("password",encryptPassword);
param.put("selfPassword",sm4Password);
param.put("loginName",userName);
param.put("timeStamp", UUID.randomUUID().toString());
ResponseEntity<AnYanResult> responseEntity = RestTemplateUtil.postExchangeForGetToken(AnYanApiEnum.PUBLIC_NETWORK_AUTH_TOKEN, param,AnYanResult.class);
//安眼提供的接口包过深 ,先从AnYanResult对象中取出加密的密文,后在解密密文拿出 AuthResult对象 , 再从AuthResult对象中拿出 access_token
try {
AnYanResult anYanResult = responseEntity.getBody();
if(ObjectUtil.isNotEmpty(anYanResult) && ObjectUtil.isNotEmpty(anYanResult.getData())){
String decryptAuthResult = SM4Utils.decryptSM4((String) anYanResult.getData());
AuthResult authResult = JSON.parseObject(decryptAuthResult).toJavaObject(AuthResult.class);
if(null != authResult && null != authResult.getAccess_token()){
token = authResult.getAccess_token();
int expireSeconds = ObjectUtil.isNotEmpty(authResult.getExpires_in())? authResult.getExpires_in() : 7200;
redisClientUtil.set(new RedisKeyPrefix(expireSeconds,AnYanConstants.AN_YAN_API_TOKEN_PREFIX),"publicToken", token);
}
}
} catch (Exception e) {
e.printStackTrace();
ExceptionAssertsUtil.fail("获取安眼系统token失败");
}
}
return token;
}
}
@@ -30,6 +30,18 @@ public class AnYanProperties {
*clientSecret
*/
private String clientSecret = "";
/**
*公网可访问的接口地址 (目前或者大屏调转的toekn使用)
*/
private String publicHost = "";
/**
* 公网环境的鉴权账号 (目前或者大屏调转的toekn使用)
*/
private String publicUserNmae = "";
/**
*公网环境的鉴权密码 (目前或者大屏调转的toekn使用)
*/
private String publicPassWrod = "";
/**
*链接超时时间
*/
@@ -1,9 +1,9 @@
package com.renkang.anyan.config;
import com.renkang.anyan.enums.AnYanApiEnum;
import com.renkang.anyan.model.vo.AnYanResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.SpringContextUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
@@ -39,7 +39,7 @@ public class RestTemplateUtil {
}
/**
* 通用调用方法
* 请求接口访问 token
* @param api 接口
* @param requestBody 参数
* @return ResponseEntity
@@ -50,6 +50,18 @@ public class RestTemplateUtil {
return getRestTemplate().exchange(url, api.getHttpMethod(), requestEntity, responseType);
}
/**
* 公网请求接口访问 token
* @param api 接口
* @param requestBody 参数
* @return ResponseEntity
*/
public static <T> ResponseEntity<T> postExchangeForGetToken(AnYanApiEnum api,Object requestBody,Class<T> responseType) {
String url = getProperties().getPublicHost() + api.getMethodPath() + api.getMethodParam();
HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody);
return getRestTemplate().exchange(url, api.getHttpMethod(), requestEntity, responseType);
}
/**
* 通用调用方法
* @param api 请求接口
@@ -57,10 +69,10 @@ public class RestTemplateUtil {
* @param requestBody body参数
* @return Result对象
*/
public static Result<Object> postExchange(AnYanApiEnum api, HttpHeaders headers,Object requestBody) {
public static AnYanResult<Object> postExchange(AnYanApiEnum api, HttpHeaders headers, Object requestBody) {
String url = getProperties().getHost() + api.getMethodPath() +api.getMethodParam();
HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody,headers);
return responseHandler(getRestTemplate().exchange(url, api.getHttpMethod(), requestEntity, Result.class));
return responseHandler(getRestTemplate().exchange(url, api.getHttpMethod(), requestEntity, AnYanResult.class));
}
/**
@@ -68,11 +80,11 @@ public class RestTemplateUtil {
* @param entity
* @return
*/
private static <T extends Result<Object>> Result<Object> responseHandler(ResponseEntity<T> entity) {
private static <T extends AnYanResult<Object>> AnYanResult<Object> responseHandler(ResponseEntity<T> entity) {
if(HttpStatus.OK.equals(entity.getStatusCode()) && ObjectUtils.isNotEmpty(entity.getBody())){
return entity.getBody();
}else{
return Result.error("天眼系统API调用失败");
return AnYanResult.error("天眼系统API调用失败");
}
}
@@ -63,7 +63,12 @@ public enum AnYanApiEnum {
/**
*11.健康小屋详细数据查询
*/
HEALTH_PLACE_ROOM_INFO_LIST("/aygc-znhpt-sys/0/aystatistics/initEmpHealthRoomCheckinInfoPages","", HttpMethod.POST);
HEALTH_PLACE_ROOM_INFO_LIST("/aygc-znhpt-sys/0/aystatistics/initEmpHealthRoomCheckinInfoPages","", HttpMethod.POST),
/**
* 12.从外网地址获取安眼token接口
*/
PUBLIC_NETWORK_AUTH_TOKEN("/aygc-service-sys/0/api/xj/outside/getToken","", HttpMethod.POST);
/**
* 接口路径
@@ -0,0 +1,170 @@
package com.renkang.anyan.model.vo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.jeecg.common.constant.CommonConstant;
import java.io.Serializable;
@Data
@Schema(title = "安眼系统接口返回对象", description = "安眼系统接口返回对象")
public class AnYanResult<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 成功标志
*/
@Schema(title = "成功标志")
private boolean success = true;
/**
* 返回处理消息
*/
@Schema(title = "返回处理消息")
private String message = "";
/**
* 返回代码
*/
@Schema(title = "返回代码")
private Integer code = 0;
/**
* 返回数据对象 data
*/
@Schema(title = "返回数据对象")
private T data;
/**
* 时间戳
*/
@Schema(title = "时间戳")
private long timestamp = System.currentTimeMillis();
@JsonIgnore
private String onlTable;
public AnYanResult() {
}
/**
* 兼容VUE3版token失效不跳转登录页面
*
* @param code
* @param message
*/
public AnYanResult(Integer code, String message) {
this.code = code;
this.message = message;
}
public static <T> AnYanResult<T> ok() {
AnYanResult<T> r = new AnYanResult<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
return r;
}
public static <T> AnYanResult<T> ok(String msg) {
AnYanResult<T> r = new AnYanResult<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
//Result OK(String msg)方法会造成兼容性问题 issues/I4IP3D
r.setData((T) msg);
r.setMessage(msg);
return r;
}
public static <T> AnYanResult<T> ok(T data) {
AnYanResult<T> r = new AnYanResult<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setData(data);
return r;
}
public static <T> AnYanResult<T> OK() {
AnYanResult<T> r = new AnYanResult<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
return r;
}
/**
* 此方法是为了兼容升级所创建
*
* @param msg
* @param <T>
* @return
*/
public static <T> AnYanResult<T> OK(String msg) {
AnYanResult<T> r = new AnYanResult<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setMessage(msg);
//Result OK(String msg)方法会造成兼容性问题 issues/I4IP3D
r.setData((T) msg);
return r;
}
public static <T> AnYanResult<T> OK(T data) {
AnYanResult<T> r = new AnYanResult<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setData(data);
return r;
}
public static <T> AnYanResult<T> OK(String msg, T data) {
AnYanResult<T> r = new AnYanResult<T>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setMessage(msg);
r.setData(data);
return r;
}
public static <T> AnYanResult<T> error(String msg, T data) {
AnYanResult<T> r = new AnYanResult<T>();
r.setSuccess(false);
r.setCode(CommonConstant.SC_INTERNAL_SERVER_ERROR_500);
r.setMessage(msg);
r.setData(data);
return r;
}
public static <T> AnYanResult<T> error(String msg) {
return error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500, msg);
}
public static <T> AnYanResult<T> error(int code, String msg) {
AnYanResult<T> r = new AnYanResult<T>();
r.setCode(code);
r.setMessage(msg);
r.setSuccess(false);
return r;
}
/**
* 无权限访问返回结果
*/
public static <T> AnYanResult<T> noauth(String msg) {
return error(CommonConstant.SC_JEECG_NO_AUTHZ, msg);
}
public AnYanResult<T> success(String message) {
this.message = message;
this.code = CommonConstant.SC_OK_200;
this.success = true;
return this;
}
public AnYanResult<T> error500(String message) {
this.message = message;
this.code = CommonConstant.SC_INTERNAL_SERVER_ERROR_500;
this.success = false;
return this;
}
}
@@ -3,7 +3,7 @@ package com.renkang.anyan.utils;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.api.vo.Result;
import com.renkang.anyan.model.vo.AnYanResult;
import java.util.stream.Collectors;
@@ -13,8 +13,8 @@ import java.util.stream.Collectors;
*/
public class PageResultToBeanUtil<T> {
public IPage<T> transform(Result<Object> result,Class<T> tClass) {
IPage<?> page = BeanUtil.toBean(result.getResult(), Page.class);
public IPage<T> transform(AnYanResult<Object> result, Class<T> tClass) {
IPage<?> page = BeanUtil.toBean(result.getData(), Page.class);
IPage<T> iPage = new Page<>();
BeanUtil.copyProperties(page,iPage,"records");
if(page.getTotal() > 0){
@@ -0,0 +1,47 @@
package com.renkang.anyan.utils;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.SM4;
/**
* XJ安眼平台提供的数据加密工具类 仅用于安眼系统外部登录接口的对接
*/
public class SM4Utils {
private static final String privateKey = "5tgb6yhn7ujm8ik,";
// private static final String privateKey = "123456789qwertyu";
private static final String iv = "5tgb6yhn7ujm8ik,";
// private static final String iv = "abcdefghi1234567";
private static SM4 sm4 = null;
private static SM4 getInstance() {
if (sm4 == null) {
sm4 = new SM4(Mode.CBC, Padding.PKCS5Padding, privateKey.getBytes(), iv.getBytes());
}
return sm4;
}
/**
* @description 加密
* @author xj
* @time 2023/8/17
*/
public static String encryptSM4(String needEncryptText) {
return getInstance().encryptBase64(needEncryptText);
}
/**
* @description 解密
* @author xj
* @time 2023/8/17
*/
public static String decryptSM4(String encryptText) {
if (encryptText == null || encryptText.isEmpty()) return "";
return getInstance().decryptStr(encryptText);
}
}
@@ -0,0 +1,115 @@
package com.renkang.anyan.utils;
import cn.hutool.core.util.StrUtil;
import javax.crypto.Cipher;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
/**
* 安眼平台提供的数据加密工具类 仅用于安眼系统外部登录接口的对接
*/
public class StringUtils {
/**
* 公钥加密方法
*
* @param publicKeyText 公钥
* @param text 将要加密的信息
* @return Base64编码的字符串
* @throws Exception
*/
public static String encryptByPublicKey(String publicKeyText, String text) throws Exception {
// 返回按照 X.509 标准进行编码的密钥的字节
// x509EncodedKeySpec2 是一种规范、规格
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(org.apache.commons.codec.binary.Base64.decodeBase64(publicKeyText));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// 让密钥工厂按照指定的 规范 生成公钥
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
// 对加密初始化,使用加密模式,公钥加密
// Cipher.ENCRYPT_MODE 可以用 1 代替
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(text.getBytes());
// 返回 Base64编码的字符串
return org.apache.commons.codec.binary.Base64.encodeBase64String(result);
}
public static String base64Encode(String input) {
return Base64.getEncoder().encodeToString(input.getBytes());
}
public static String base64Decode(String encodedInput) {
byte[] decodedBytes = Base64.getDecoder().decode(encodedInput);
return new String(decodedBytes);
}
public static String preprocessJsonString(String jsonStr) {
String a = StrUtil.removeAll(jsonStr, ' ', '\t', '\r', '\n');
String[] searchList = {"\":\"", "\",\"", "{\"", "\"}", "\":"};
String[] replacementList = {"$is$", "$center$", "$left$", "$right$", "$start$"};
String b = org.apache.commons.lang3.StringUtils.replaceEach(a, searchList, replacementList);
String c = b.replace("\"", "\\\"");
return org.apache.commons.lang3.StringUtils.replaceEach(c, replacementList, searchList);
}
/**
* 提取文件名中的扩展名
*
* @param fileName 文件名
* @param needDot 需要点
* @return 文件扩展名,如果文件名中没有扩展名则返回 null
*/
public static String getFileExtension(String fileName, boolean needDot) {
// 检查文件名是否为 null 或空字符串
if (fileName == null || fileName.isEmpty()) {
return null;
}
// 找到最后一个点的位置
int lastDotIndex = fileName.lastIndexOf('.');
// 如果找不到点,或者点在字符串的第一个位置,返回 null
if (lastDotIndex == -1 || lastDotIndex == 0) {
return null;
}
return fileName.substring(needDot ? lastDotIndex : (lastDotIndex + 1));
}
/**
* 获取路径的最后一个元素(文件名或目录名)
*
* @param pathOrUrl 文件路径或 URL
* @return 路径的最后一个元素
*/
public static String baseName(String pathOrUrl) {
if (pathOrUrl == null || pathOrUrl.isEmpty()) {
return "";
}
try {
// 尝试将字符串解析为 URI
URI uri = new URI(pathOrUrl);
// 获取 URI 的路径部分
String path = uri.getPath();
// 使用 Path 类获取路径的最后一个元素
Path filePath = Paths.get(path);
return filePath.getFileName().toString();
} catch (URISyntaxException e) {
// 如果解析 URI 失败,则直接将字符串作为路径处理
Path filePath = Paths.get(pathOrUrl);
return filePath.getFileName().toString();
}
}
}