From fd80fcedf5e523c2923199a387cd4962bb3249d0 Mon Sep 17 00:00:00 2001 From: shenym3 Date: Wed, 13 Dec 2023 10:49:45 +0800 Subject: [PATCH 1/4] =?UTF-8?q?[fix]:[][=E5=8F=91=E9=80=81=E5=BC=95?= =?UTF-8?q?=E5=AF=BC=E5=88=86=E4=BA=AB=E6=B6=88=E6=81=AF]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/jeesite/modules/util/PageUtil.java | 44 +++++++ .../com/jeesite/modules/util/RedisUtils.java | 109 ++++++++++++++++++ .../jeesite/modules/util/SwaggerUtils.java | 23 ++++ 3 files changed, 176 insertions(+) create mode 100644 src/main/java/com/jeesite/modules/util/PageUtil.java create mode 100644 src/main/java/com/jeesite/modules/util/RedisUtils.java create mode 100644 src/main/java/com/jeesite/modules/util/SwaggerUtils.java diff --git a/src/main/java/com/jeesite/modules/util/PageUtil.java b/src/main/java/com/jeesite/modules/util/PageUtil.java new file mode 100644 index 0000000..157d5a1 --- /dev/null +++ b/src/main/java/com/jeesite/modules/util/PageUtil.java @@ -0,0 +1,44 @@ +package com.asiainfo.ai.admin.utils; + +import java.util.List; + +public class PageUtil { + + public static List getPageList(List list, Integer pageNum, Integer pageSize) { + if (list == null) { + return null; + } + if (list.size() == 0) { + return null; + } + + // 记录总数 + Integer count = list.size(); + // 页数,一共多少页 + int pageCount; + + //取余计算总页数 + if (count % pageSize == 0) { + pageCount = count / pageSize; + } else { + pageCount = count / pageSize + 1; + } + + // 开始索引 + int fromIndex; + // 结束索引 + int toIndex; + + if (!pageNum.equals(pageCount)) { + //从第几个数据开始查 + fromIndex = (pageNum - 1) * pageSize; + toIndex = fromIndex + pageSize; + } else { + fromIndex = (pageNum - 1) * pageSize; + toIndex = count; + } + + return list.subList(fromIndex, toIndex); + } + +} diff --git a/src/main/java/com/jeesite/modules/util/RedisUtils.java b/src/main/java/com/jeesite/modules/util/RedisUtils.java new file mode 100644 index 0000000..7381cb9 --- /dev/null +++ b/src/main/java/com/jeesite/modules/util/RedisUtils.java @@ -0,0 +1,109 @@ +package com.asiainfo.ai.admin.utils; + +import cn.hutool.json.JSONUtil; +import com.asiainfo.ai.admin.constant.ApisConstant; +import com.asiainfo.ai.admin.constant.UcConstant; +import com.asiainfo.ai.admin.controller.vo.api.ApiUserRedisBean; +import com.asiainfo.ai.core.constants.RedisConstant; +import com.google.common.base.Strings; +import com.google.common.collect.Maps; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.data.redis.connection.StringRedisConnection; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@Slf4j +@Component +public class RedisUtils { + + private final StringRedisTemplate stringRedisTemplate; + + private final StringRedisTemplate testStringRedisTemplate; + + private final StringRedisTemplate productStringRedisTemplate; + + public RedisUtils(@Qualifier(ApisConstant.DEVELOP_STRING_REDIS_TEMPLATE) StringRedisTemplate stringRedisTemplate, + @Qualifier(ApisConstant.TEST_STRING_REDIS_TEMPLATE) StringRedisTemplate testStringRedisTemplate, + @Qualifier(ApisConstant.PRODUCTION_STRING_REDIS_TEMPLATE) StringRedisTemplate productStringRedisTemplate) { + this.stringRedisTemplate = stringRedisTemplate; + + this.testStringRedisTemplate = testStringRedisTemplate; + this.productStringRedisTemplate = productStringRedisTemplate; + } + + public void deleteFromRedisAll() { + Set devKeys = stringRedisTemplate.keys(UcConstant.API_USER_KEY_PREFIX + "*"); + Set productKeys = productStringRedisTemplate.keys(UcConstant.API_USER_KEY_PREFIX + "*"); + stringRedisTemplate.delete(devKeys); + productStringRedisTemplate.delete(productKeys); + try { + Set testKeys = testStringRedisTemplate.keys(UcConstant.API_USER_KEY_PREFIX + "*"); + testStringRedisTemplate.delete(testKeys); + } catch (Exception e) { + log.error("更新测试域redis出错", e); + } + } + + public void deleteFromRedis(String apiUserId) { + String key = Strings.lenientFormat("%s%s%s", UcConstant.API_USER_KEY_PREFIX, apiUserId, "*"); + Set devKeys = stringRedisTemplate.keys(key); + Set productKeys = productStringRedisTemplate.keys(key); + stringRedisTemplate.delete(devKeys); + productStringRedisTemplate.delete(productKeys); + try { + Set testKeys = testStringRedisTemplate.keys(key); + testStringRedisTemplate.delete(testKeys); + } catch (Exception e) { + log.error("更新测试域redis出错", e); + } + } + + + public void writeToRedis(List apiUserRedisBeans, String profile) { + if (RedisConstant.DEV.equals(profile)) { + writeToRedis(apiUserRedisBeans, stringRedisTemplate, profile); + return; + } + if (RedisConstant.TEST.equals(profile)) { + writeToRedis(apiUserRedisBeans, testStringRedisTemplate, profile); + return; + } + if (RedisConstant.PRODUCT.equals(profile)) { + writeToRedis(apiUserRedisBeans, productStringRedisTemplate, profile); + } + } + + private void writeToRedis(List apiUserRedisBeans, StringRedisTemplate stringRedisTemplate, String profile) { + stringRedisTemplate.executePipelined( + (RedisCallback) connection -> { + StringRedisConnection stringRedisConn = (StringRedisConnection) connection; + for (ApiUserRedisBean apiUserRedisBean : apiUserRedisBeans) { + String apiUserId = apiUserRedisBean.getApiUserId(); + String key = getApiUserCacheKey(apiUserId, profile); + stringRedisConn.set(key, JSONUtil.toJsonStr(apiUserRedisBean.getApiIdList())); + } + //必须返回null + return null; + }); + } + + private static String getApiUserCacheKey(String apiUser, String profile) { + return Strings.lenientFormat("%s%s:%s", UcConstant.API_USER_KEY_PREFIX, apiUser, profile); + } + + public Map getAllStringRedisTemplate() { + HashMap stringRedisTemplateMap = Maps.newHashMap(); + stringRedisTemplateMap.put(RedisConstant.DEV, stringRedisTemplate); + stringRedisTemplateMap.put(RedisConstant.TEST, testStringRedisTemplate); + stringRedisTemplateMap.put(RedisConstant.PRODUCT, productStringRedisTemplate); + return stringRedisTemplateMap; + } + +} diff --git a/src/main/java/com/jeesite/modules/util/SwaggerUtils.java b/src/main/java/com/jeesite/modules/util/SwaggerUtils.java new file mode 100644 index 0000000..1dcc936 --- /dev/null +++ b/src/main/java/com/jeesite/modules/util/SwaggerUtils.java @@ -0,0 +1,23 @@ +package com.asiainfo.ai.admin.utils; + +import com.asiainfo.mlp.common.core.config.MlpPlatformConfig; +import io.swagger.v3.oas.models.info.Contact; +import io.swagger.v3.oas.models.info.Info; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public final class SwaggerUtils { + + public static Info buildApiDocInfo(MlpPlatformConfig mlpPlatformConfig) { + Info info = new Info(); + Contact contact = new Contact(); + info.title(mlpPlatformConfig.getPlatform()); + info.description(mlpPlatformConfig.getPlatformDesc()); + info.version(mlpPlatformConfig.getPlatformVersion()); + contact.setName(mlpPlatformConfig.getPlatformLinkman()); + contact.setEmail(mlpPlatformConfig.getPlatformLinkEmail()); + info.contact(contact); + return info; + } + +} -- Gitee From 989567c5111ec0b996dcdac61d1407cacb0d362a Mon Sep 17 00:00:00 2001 From: shenym3 Date: Wed, 13 Dec 2023 10:51:43 +0800 Subject: [PATCH 2/4] =?UTF-8?q?[fix]:[][=E7=B3=BB=E7=BB=9F=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=BC=B9=E5=87=BA=E7=99=BB=E5=BD=95=E4=BA=8C=E7=BB=B4?= =?UTF-8?q?=E7=A0=81]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jeesite/modules/util/SwaggerDocUtil.java | 201 ++++++++++++++++++ .../modules/util/TreeNodeConverter.java | 87 ++++++++ 2 files changed, 288 insertions(+) create mode 100644 src/main/java/com/jeesite/modules/util/SwaggerDocUtil.java create mode 100644 src/main/java/com/jeesite/modules/util/TreeNodeConverter.java diff --git a/src/main/java/com/jeesite/modules/util/SwaggerDocUtil.java b/src/main/java/com/jeesite/modules/util/SwaggerDocUtil.java new file mode 100644 index 0000000..464cb68 --- /dev/null +++ b/src/main/java/com/jeesite/modules/util/SwaggerDocUtil.java @@ -0,0 +1,201 @@ +package com.asiainfo.ai.admin.utils; + +import com.asiainfo.ai.admin.enums.MlpPlatformService; +import com.asiainfo.mlp.common.core.config.MlpPlatformConfig; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.util.MinimalPrettyPrinter; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import io.swagger.models.*; +import io.swagger.models.auth.ApiKeyAuthDefinition; +import io.swagger.models.auth.In; +import io.swagger.models.auth.OAuth2Definition; +import io.swagger.models.auth.SecuritySchemeDefinition; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.ObjectProperty; +import io.swagger.models.properties.StringProperty; +import io.swagger.v3.core.util.Json; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.web.util.UriUtils; + +import java.nio.charset.Charset; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Description: Date: 2019-05-29 17:03 + * + * @author liyi + */ +@Slf4j +@Service +public class SwaggerDocUtil { + private final static Pattern REF_DEF_PATTERN = Pattern.compile("\"\\$ref\":\"#/definitions/([^\"]+)\""); + private final static Pattern REF_DEF_PATTERN2 = Pattern.compile("\"\\$ref\" : \"#/definitions/(.+)\""); + + private SwaggerDocUtil() { + + } + + private static String buildJson(String key, HttpMethod method, Operation operate, Map refMap) { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode docNode = mapper.createObjectNode(); + ObjectNode pathsNode = mapper.createObjectNode(); + ObjectNode operateNode = mapper.createObjectNode(); + operateNode.putPOJO(method.name().toLowerCase(), operate); + pathsNode.putPOJO(key, operateNode); + docNode.putPOJO("paths", pathsNode); + docNode.putPOJO("definitions", refMap); + String docJson = ""; + try { + docJson = Json.mapper().writer(new MinimalPrettyPrinter()).writeValueAsString(docNode); + } catch (JsonProcessingException e) { + log.warn("build swagger json error", e); + } + docJson = docJson.replace("«", "<").replace("»", ">"); + return codeRefJson(docJson, true); + } + + private static String codeRefJson(String docJson, boolean isEncode) { + StringBuffer sb = new StringBuffer(docJson.length()); + Matcher matcher = REF_DEF_PATTERN.matcher(docJson); + while (matcher.find()) { + String m = matcher.group(); + int start = matcher.start(); + String prefix = m.substring(0, matcher.start(1) - start).replace("$", "\\$"); + String suffix = m.substring(matcher.end(1) - start, matcher.end() - start); + if ("String".equalsIgnoreCase(matcher.group(1))) { + matcher.appendReplacement(sb, "\"type\" : \"string\""); + } else { + String newStr = isEncode ? encodeRef(matcher.group(1)) : decodeRef(matcher.group(1)); + matcher.appendReplacement(sb, prefix + newStr + suffix); + } + } + matcher.appendTail(sb); + return sb.toString(); + } + + + private static Map parseRefDef(Operation operate, final Map definitions) { + Map resultMap = Maps.newHashMap(); + if (operate != null) { + String json = Json.pretty(operate); + Matcher matcher = REF_DEF_PATTERN2.matcher(json); + while (matcher.find()) { + String refId = matcher.group(1); + Model model = definitions.get(refId); + if (model != null) { + resultMap.put(refId, model); + resultMap.putAll(parseModelRefDef(refId, model, definitions)); + } + } + } + return resultMap; + } + + private static Map parseModelRefDef(String pRefId, Model model, final Map definitions) { + String json = Json.pretty(model); + Map resultMap = Maps.newHashMap(); + Matcher matcher = REF_DEF_PATTERN2.matcher(json); + while (matcher.find()) { + String refId = matcher.group(1); + if (definitions.get(refId) != null && !refId.equals(pRefId)) { + resultMap.put(refId, definitions.get(refId)); + resultMap.putAll(parseModelRefDef(refId, definitions.get(refId), definitions)); + } + } + return resultMap; + } + + public static Map buildSecurityDefinitions(String gatewayUrl, String grantType) { +// OAuth2Definition oauth2Def = new OAuth2Definition(); +// oauth2Def.setFlow(grantType); +// oauth2Def.setAuthorizationUrl("http://" + gatewayUrl + "/authc/oauth/authorize"); +// oauth2Def.setTokenUrl("http://" + gatewayUrl + "/authc/oauth/token"); +// oauth2Def.setDescription("通过授权码模式,获取授权码,再通过授权码换取token"); + OAuth2Definition oauth2Def2 = new OAuth2Definition(); + oauth2Def2.setFlow("application"); + oauth2Def2.setDescription("通过客户端模式,获取访问token"); + oauth2Def2.setTokenUrl(StringUtils.removeEnd(gatewayUrl, "/") + "/uc/oauth/token"); + ApiKeyAuthDefinition bearerDef = new ApiKeyAuthDefinition(); + bearerDef.setName("Authorization"); + bearerDef.setIn(In.HEADER); + bearerDef.setDescription(">\n" + + " Authorization header 必须按以下语法:\n" + + " `Bearer: xxxxxx.yyyyyyy.zzzzzz`"); + return ImmutableMap.of("oauth2-client", oauth2Def2, "Bearer", bearerDef); + } + + public static Info buildApiDocInfo(MlpPlatformConfig mlpPlatformConfig) { + Info info = new Info(); + Contact contact = new Contact(); + info.title(mlpPlatformConfig.getPlatform()); + info.description(mlpPlatformConfig.getPlatformDesc()); + info.version(mlpPlatformConfig.getPlatformVersion()); + contact.setName(mlpPlatformConfig.getPlatformLinkman()); + contact.setEmail(mlpPlatformConfig.getPlatformLinkEmail()); + info.contact(contact); + return info; + } + + public static Map buildDefaultDefinitionMap(String[] serviceId) { + Map definitionMap = Maps.newHashMap(); + if (ArrayUtils.contains(serviceId, MlpPlatformService.DSEM.getCode())) { + ModelImpl errorModel = new ModelImpl() + .property("processInfo", new StringProperty().description("处理信息")) + .property("processStatus", new StringProperty().description("处理状态")) + .property("success", new BooleanProperty()._default(false).description("是否处理成功")) + .property("value", new StringProperty().description("响应结果数据")); + definitionMap.put("DSEM_Error", errorModel); + } else { + ModelImpl errorModel = new ModelImpl() + .property("code", new StringProperty().description("处理业务状态码")) + .property("message", new StringProperty().description("处理信息")) + .property("data", new ObjectProperty().description("响应结果数据")); + definitionMap.put("API_Error", errorModel); + } + return definitionMap; + } + + public static Map buildDefaultRespMap(String serviceId) { + RefModel errorRefModel = new RefModel(); + if (MlpPlatformService.DSEM.getCode().equalsIgnoreCase(serviceId)) { + errorRefModel.set$ref("#/definitions/DSEM_Error"); + } else { + errorRefModel.set$ref("#/definitions/API_Error"); + } + Map respMap = Maps.newHashMap(); + respMap.put("400", new Response().description("Bad Request,请求报文语法错误或参数错误").responseSchema(errorRefModel)); + respMap.put("401", new Response().description("Unauthorized,未认证,接口调用未传token,或token无效").responseSchema(errorRefModel)); + respMap.put("403", new Response().description("Forbidden,未授权禁止访问").responseSchema(errorRefModel)); + respMap.put("500", new Response().description("Internal Server Error,服务器内部错误,无法完成请求").responseSchema(errorRefModel)); + respMap.put("504", new Response().description("Gateway Time-out,请求网关超时").responseSchema(errorRefModel)); + respMap.put("503", new Response().description("Service Unavailable,服务不可用").responseSchema(errorRefModel)); + + return respMap; + } + + public static void correctParamList(List paramList) { + paramList.forEach(param -> { + if ("path".equalsIgnoreCase(param.getIn())) { + param.setRequired(true); + } + }); + } + + public static String encodeRef(String str) { + return UriUtils.encode(str, Charset.forName("UTF-8")); + } + + public static String decodeRef(String str) { + return UriUtils.decode(str, Charset.forName("UTF-8")); + } +} \ No newline at end of file diff --git a/src/main/java/com/jeesite/modules/util/TreeNodeConverter.java b/src/main/java/com/jeesite/modules/util/TreeNodeConverter.java new file mode 100644 index 0000000..6aee2db --- /dev/null +++ b/src/main/java/com/jeesite/modules/util/TreeNodeConverter.java @@ -0,0 +1,87 @@ +package com.asiainfo.ai.admin.utils; + +import cn.hutool.core.util.ArrayUtil; +import com.asiainfo.ai.admin.controller.vo.TreeNode; +import com.asiainfo.ai.admin.exception.BaseException; +import com.asiainfo.ai.admin.exception.ErrorType; +import com.google.common.collect.Maps; +import org.springframework.util.ReflectionUtils; + +import java.lang.reflect.Field; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Description: Date: 2019-04-01 22:30 + * + * @author liyi + */ +public class TreeNodeConverter { + private static final String ID_FIELD = "id"; + private static final String NAME_FIELD = "name"; + private static final String PID_FIELD = "pid"; + private static final String DESCRIPTION = "desc"; + + /** + * 根据模块列表,生成树形结构集合 + * + * @param list 需要转换的list集合 + * @param parentId 父节点id + * @param additionField 附加信息字段 + * @return 返回树形结构数据集合 + */ + public static List convert(Collection list, String parentId, String[] additionField) { + return convert(list, parentId, ID_FIELD, PID_FIELD, NAME_FIELD, DESCRIPTION, additionField); + } + + /** + * 根据模块列表,生成树形结构集合 + * + * @param list 需要转换的list集合 + * @param parentId 父节点id + * @param idField id字段 + * @param nameField 名称字段 + * @param pidField pid字段 + * @param additionField 附加信息字段 + * @return 返回树形结构数据集合 + */ + public static List convert(Collection list, + String parentId, + String idField, + String pidField, + String nameField, + String description, + String[] additionField) { + return list.stream() + .filter(it -> getFieldValue(it, pidField).equalsIgnoreCase(parentId)) + .map(it -> { + String id = getFieldValue(it, idField); + Map additionMap = Maps.newHashMap(); + if (ArrayUtil.isNotEmpty(additionField)) { + for (String field : additionField) { + additionMap.put(field, getFieldValue(it, field)); + } + } + return TreeNode.builder() + .id(id) + .pid(parentId) + .name(getFieldValue(it, nameField)) + .desc(description) + .children(convert(list, id, idField, pidField, nameField, description, additionField)) + .addition(additionMap) + .build(); + }) + .collect(Collectors.toList()); + } + + private static String getFieldValue(T t, String fieldName) { + Field field = ReflectionUtils.findField(t.getClass(), fieldName); + if (null == field) { + throw new BaseException(ErrorType.SYSTEM_ERROR, "树形结构转换失败,字段" + fieldName + "不存在"); + } + ReflectionUtils.makeAccessible(field); + return String.valueOf(ReflectionUtils.getField(field, t)); + } +} -- Gitee From 334655eae344b9eb947c6e2eb778b3d506f87539 Mon Sep 17 00:00:00 2001 From: shenym3 Date: Wed, 13 Dec 2023 10:53:32 +0800 Subject: [PATCH 3/4] =?UTF-8?q?[fix]:[][Workbook=E8=B5=84=E6=BA=90?= =?UTF-8?q?=E6=9C=AA=E5=85=B3=E9=97=AD]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/jeesite/modules/util/WriteExcel.java | 116 ++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 src/main/java/com/jeesite/modules/util/WriteExcel.java diff --git a/src/main/java/com/jeesite/modules/util/WriteExcel.java b/src/main/java/com/jeesite/modules/util/WriteExcel.java new file mode 100644 index 0000000..811292a --- /dev/null +++ b/src/main/java/com/jeesite/modules/util/WriteExcel.java @@ -0,0 +1,116 @@ +package com.asiainfo.ai.data.util; + +import lombok.extern.slf4j.Slf4j; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +import java.io.*; +import java.util.List; +import java.util.Objects; + +/** + * @author adward + */ +@Slf4j +public class WriteExcel { + + private static final String EXCEL_XLS = "xls"; + private static final String EXCEL_XLSX = "xlsx"; + + public WriteExcel() { + } + + public static void writeExcel(List> dataList, String finalXlsxPath) { + OutputStream out = null; + Workbook workBook = null; + try { + // 读取Excel文档 + File finalXlsxFile = new File(finalXlsxPath); + //fixbug: [PRDAI_ISSUE_722] 问题修复:Workbook资源未关闭 + workBook = getWorkbook(finalXlsxFile); + if (Objects.isNull(workBook)) { + log.error("workBook对象为空"); + return; + } + // sheet 对应一个工作页 + Sheet sheet = workBook.getSheetAt(0); + + // 删除原有数据,除了属性列 + int rowNumber = sheet.getLastRowNum(); + for (int i = 1; i <= rowNumber; i++) { + Row row = sheet.getRow(i); + sheet.removeRow(row); + } + // 创建文件输出流,输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效 + out = new FileOutputStream(finalXlsxPath); + workBook.write(out); + /** + * 往Excel中写新数据 + */ + for (int j = 0; j < dataList.size(); j++) { + // 创建一行:从第二行开始,跳过属性列 + Row row = sheet.createRow(j + 1); + // 得到要插入的每一条记录 + List dataStr = dataList.get(j); + for (int k = 0; k < dataStr.size(); k++) { + Cell first = row.createCell(k); + first.setCellValue(dataStr.get(k)); + } + } + // 创建文件输出流,准备输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效 + out = new FileOutputStream(finalXlsxPath); + workBook.write(out); + } catch (Exception e) { + log.error(e.getMessage(), e); + log.error("errorInfo: {}", e.getMessage()); + } finally { + try { + if (out != null) { + out.flush(); + out.close(); + } + if (workBook != null) { + workBook.close(); + } + } catch (IOException e) { + log.error(e.getMessage(), e); + log.error("errorInfo: {}", e.getMessage()); + } + } + } + + + public static Workbook getWorkbook(File file) throws Exception{ + Workbook wb = null; + FileInputStream in = null; + try { + in = new FileInputStream(file); + if (file.getName().endsWith(EXCEL_XLS)) { + // Excel 2003 + wb = new HSSFWorkbook(in); + } else if (file.getName().endsWith(EXCEL_XLSX)) { + // Excel 2007/2010 + wb = new XSSFWorkbook(in); + } + in.close(); + } catch (Exception e) { + log.error("getWorkbok error: {}", e.getMessage()); + log.error(e.getMessage(), e); + throw e; + } finally { + try { + if (in != null) { + in.close(); + } + } catch (IOException e) { + log.error("getWorkbok error: ", e); + } + } + return wb; + } + +} \ No newline at end of file -- Gitee From bb285feec7e6401e0f8623d473f7770989935a13 Mon Sep 17 00:00:00 2001 From: shenym3 Date: Wed, 13 Dec 2023 10:59:19 +0800 Subject: [PATCH 4/4] =?UTF-8?q?[fix]:[][Workbook=E8=B5=84=E6=BA=90?= =?UTF-8?q?=E6=9C=AA=E5=85=B3=E9=97=AD]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/jeesite/modules/util/DESUtil.java | 185 ++++++++++++++++++ 1 file changed, 185 insertions(+) create mode 100644 src/main/java/com/jeesite/modules/util/DESUtil.java diff --git a/src/main/java/com/jeesite/modules/util/DESUtil.java b/src/main/java/com/jeesite/modules/util/DESUtil.java new file mode 100644 index 0000000..9936c3f --- /dev/null +++ b/src/main/java/com/jeesite/modules/util/DESUtil.java @@ -0,0 +1,185 @@ +package com.asiainfo.ai.gateway.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.crypto.*; +import javax.crypto.spec.DESKeySpec; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; + +/** + * DES加解密工具类 + * + * @author gaofan + */ +public class DESUtil { + private static final Logger LOGGER = LoggerFactory.getLogger(DESUtil.class); + + private static final String DES_ALGORITHM = "DES"; + + /** + * DES加密 + * + * @param plainData 原始字符串 + * @param secretKey 加密密钥 + * @return 加密后的字符串 + */ + public static String encryption(String plainData, String secretKey) throws Exception { + try { + Cipher cipher = Cipher.getInstance(DES_ALGORITHM); + cipher.init(Cipher.ENCRYPT_MODE, generateKey(secretKey)); + // 为了防止解密时报javax.crypto.IllegalBlockSizeException: Input length must + // be multiple of 8 when decrypting with padded cipher异常, + // 不能把加密后的字节数组直接转换成字符串 + byte[] buf = cipher.doFinal(plainData.getBytes()); + return Base64Utils.encode(buf); + } catch (NoSuchAlgorithmException e) { + LOGGER.error("error", e); + throw new Exception("NoSuchAlgorithmException", e); + } catch (NoSuchPaddingException e) { + LOGGER.error("error", e); + throw new Exception("NoSuchPaddingException", e); + } catch (InvalidKeyException e) { + LOGGER.error("error", e); + throw new Exception("InvalidKeyException", e); + } catch (IllegalBlockSizeException e) { + LOGGER.error("error", e); + throw new Exception("IllegalBlockSizeException", e); + } catch (BadPaddingException e) { + LOGGER.error("error", e); + throw new Exception("BadPaddingException", e); + } + } + + /** + * DES解密 + * + * @param secretData 密码字符串 + * @param secretKey 解密密钥 + * @return 原始字符串 + */ + public static String decryption(String secretData, String secretKey) throws Exception { + try { + Cipher cipher = Cipher.getInstance(DES_ALGORITHM); + cipher.init(Cipher.DECRYPT_MODE, generateKey(secretKey)); + byte[] buf = cipher.doFinal(Base64Utils.decode(secretData.toCharArray())); + return new String(buf); + } catch (NoSuchAlgorithmException e) { + LOGGER.error("error", e); + throw new Exception("NoSuchAlgorithmException", e); + } catch (NoSuchPaddingException e) { + LOGGER.error("error", e); + throw new Exception("NoSuchPaddingException", e); + } catch (InvalidKeyException e) { + LOGGER.error("error", e); + throw new Exception("InvalidKeyException", e); + } catch (IllegalBlockSizeException e) { + LOGGER.error("error", e); + throw new Exception("IllegalBlockSizeException", e); + } catch (BadPaddingException e) { + LOGGER.error("error", e); + throw new Exception("BadPaddingException", e); + } + } + + /** + * 获得秘密密钥 + */ + private static SecretKey generateKey(String secretKey) + throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException { + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM); + DESKeySpec keySpec = new DESKeySpec(secretKey.getBytes()); + keyFactory.generateSecret(keySpec); + return keyFactory.generateSecret(keySpec); + } + + static private class Base64Utils { + + static private char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" + .toCharArray(); + static private byte[] codes = new byte[256]; + + static { + for (int i = 0; i < 256; i++) { + codes[i] = -1; + } + for (int i = 'A'; i <= 'Z'; i++) { + codes[i] = (byte) (i - 'A'); + } + for (int i = 'a'; i <= 'z'; i++) { + codes[i] = (byte) (26 + i - 'a'); + } + for (int i = '0'; i <= '9'; i++) { + codes[i] = (byte) (52 + i - '0'); + } + codes['+'] = 62; + codes['/'] = 63; + } + + /** + * 将原始数据编码为base64编码 + */ + static private String encode(byte[] data) { + char[] out = new char[((data.length + 2) / 3) * 4]; + for (int i = 0, index = 0; i < data.length; i += 3, index += 4) { + boolean quad = false; + boolean trip = false; + int val = (0xFF & (int) data[i]); + val <<= 8; + if ((i + 1) < data.length) { + val |= (0xFF & (int) data[i + 1]); + trip = true; + } + val <<= 8; + if ((i + 2) < data.length) { + val |= (0xFF & (int) data[i + 2]); + quad = true; + } + out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)]; + val >>= 6; + out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)]; + val >>= 6; + out[index + 1] = alphabet[val & 0x3F]; + val >>= 6; + out[index + 0] = alphabet[val & 0x3F]; + } + + return new String(out); + } + + /** + * 将base64编码的数据解码成原始数据 + */ + static private byte[] decode(char[] data) { + int len = ((data.length + 3) / 4) * 3; + if (data.length > 0 && data[data.length - 1] == '=') { + --len; + } + if (data.length > 1 && data[data.length - 2] == '=') { + --len; + } + byte[] out = new byte[len]; + int shift = 0; + int accum = 0; + int index = 0; + for (int ix = 0; ix < data.length; ix++) { + int value = codes[data[ix] & 0xFF]; + if (value >= 0) { + accum <<= 6; + shift += 6; + accum |= value; + if (shift >= 8) { + shift -= 8; + out[index++] = (byte) ((accum >> shift) & 0xff); + } + } + } + if (index != out.length) { + throw new Error("miscalculated data length!"); + } + return out; + } + } +} -- Gitee