Browse Source

refactor:common报错内容修改

xiwa 2 years ago
parent
commit
4afa3be915

+ 164 - 0
iot-common/iot-common-core/src/main/java/cc/iotkit/common/utils/DateUtils.java

@@ -0,0 +1,164 @@
+package cc.iotkit.common.utils;
+
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.apache.commons.lang3.time.DateFormatUtils;
+
+import java.lang.management.ManagementFactory;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.time.*;
+import java.util.Date;
+
+/**
+ * 时间工具类
+ *
+ * @author ruoyi
+ */
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
+
+    public static final String YYYY = "yyyy";
+
+    public static final String YYYY_MM = "yyyy-MM";
+
+    public static final String YYYY_MM_DD = "yyyy-MM-dd";
+
+    public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
+
+    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
+
+    private static final String[] PARSE_PATTERNS = {
+        "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
+        "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
+        "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
+
+    /**
+     * 获取当前Date型日期
+     *
+     * @return Date() 当前日期
+     */
+    public static Date getNowDate() {
+        return new Date();
+    }
+
+    /**
+     * 获取当前日期, 默认格式为yyyy-MM-dd
+     *
+     * @return String
+     */
+    public static String getDate() {
+        return dateTimeNow(YYYY_MM_DD);
+    }
+
+    public static String getTime() {
+        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
+    }
+
+    public static String dateTimeNow() {
+        return dateTimeNow(YYYYMMDDHHMMSS);
+    }
+
+    public static String dateTimeNow(final String format) {
+        return parseDateToStr(format, new Date());
+    }
+
+    public static String dateTime(final Date date) {
+        return parseDateToStr(YYYY_MM_DD, date);
+    }
+
+    public static String parseDateToStr(final String format, final Date date) {
+        return new SimpleDateFormat(format).format(date);
+    }
+
+    public static Date dateTime(final String format, final String ts) {
+        try {
+            return new SimpleDateFormat(format).parse(ts);
+        } catch (ParseException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * 日期路径 即年/月/日 如2018/08/08
+     */
+    public static String datePath() {
+        Date now = new Date();
+        return DateFormatUtils.format(now, "yyyy/MM/dd");
+    }
+
+    /**
+     * 日期路径 即年/月/日 如20180808
+     */
+    public static String dateTime() {
+        Date now = new Date();
+        return DateFormatUtils.format(now, "yyyyMMdd");
+    }
+
+    /**
+     * 日期型字符串转化为日期 格式
+     */
+    public static Date parseDate(Object str) {
+        if (str == null) {
+            return null;
+        }
+        try {
+            return parseDate(str.toString(), PARSE_PATTERNS);
+        } catch (ParseException e) {
+            return null;
+        }
+    }
+
+    /**
+     * 获取服务器启动时间
+     */
+    public static Date getServerStartDate() {
+        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
+        return new Date(time);
+    }
+
+    /**
+     * 计算相差天数
+     */
+    public static int differentDaysByMillisecond(Date date1, Date date2) {
+        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
+    }
+
+    /**
+     * 计算两个时间差
+     */
+    public static String getDatePoor(Date endDate, Date nowDate) {
+        long nd = 1000 * 24 * 60 * 60;
+        long nh = 1000 * 60 * 60;
+        long nm = 1000 * 60;
+        // long ns = 1000;
+        // 获得两个时间的毫秒时间差异
+        long diff = endDate.getTime() - nowDate.getTime();
+        // 计算差多少天
+        long day = diff / nd;
+        // 计算差多少小时
+        long hour = diff % nd / nh;
+        // 计算差多少分钟
+        long min = diff % nd % nh / nm;
+        // 计算差多少秒//输出结果
+        // long sec = diff % nd % nh % nm / ns;
+        return day + "天" + hour + "小时" + min + "分钟";
+    }
+
+    /**
+     * 增加 LocalDateTime ==> Date
+     */
+    public static Date toDate(LocalDateTime temporalAccessor) {
+        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
+        return Date.from(zdt.toInstant());
+    }
+
+    /**
+     * 增加 LocalDate ==> Date
+     */
+    public static Date toDate(LocalDate temporalAccessor) {
+        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
+        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
+        return Date.from(zdt.toInstant());
+    }
+}

+ 0 - 24
iot-common/iot-common-core/src/main/java/cc/iotkit/common/utils/file/FileUtils.java

@@ -1,7 +1,6 @@
 package cc.iotkit.common.utils.file;
 
 import cn.hutool.core.io.FileUtil;
-import jakarta.servlet.http.HttpServletResponse;
 import lombok.AccessLevel;
 import lombok.NoArgsConstructor;
 
@@ -17,28 +16,5 @@ import java.nio.charset.StandardCharsets;
 @NoArgsConstructor(access = AccessLevel.PRIVATE)
 public class FileUtils extends FileUtil {
 
-    /**
-     * 下载文件名重新编码
-     *
-     * @param response     响应对象
-     * @param realFileName 真实文件名
-     */
-    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) {
-        String percentEncodedFileName = percentEncode(realFileName);
-        String contentDispositionValue = String.format("attachment; filename=%s;filename*=utf-8''%s", percentEncodedFileName, percentEncodedFileName);
-        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
-        response.setHeader("Content-disposition", contentDispositionValue);
-        response.setHeader("download-filename", percentEncodedFileName);
-    }
 
-    /**
-     * 百分号编码工具方法
-     *
-     * @param s 需要百分号编码的字符串
-     * @return 百分号编码后的字符串
-     */
-    public static String percentEncode(String s) {
-        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8);
-        return encode.replaceAll("\\+", "%20");
-    }
 }

+ 2 - 2
iot-common/iot-common-excel/pom.xml

@@ -19,8 +19,8 @@
         </dependency>
 
         <dependency>
-            <groupId>jakarta.servlet</groupId>
-            <artifactId>jakarta.servlet-api</artifactId>
+            <groupId>cc.iotkit</groupId>
+            <artifactId>iot-common-web</artifactId>
         </dependency>
 
         <dependency>

+ 4 - 4
iot-common/iot-common-excel/src/main/java/cc/iotkit/common/excel/utils/ExcelUtil.java

@@ -6,7 +6,7 @@ import cc.iotkit.common.excel.core.DefaultExcelListener;
 import cc.iotkit.common.excel.core.ExcelListener;
 import cc.iotkit.common.excel.core.ExcelResult;
 import cc.iotkit.common.utils.StringUtils;
-import cc.iotkit.common.utils.file.FileUtils;
+import cc.iotkit.common.web.utils.ServletUtils;
 import cn.hutool.core.collection.CollUtil;
 import cn.hutool.core.io.resource.ClassPathResource;
 import cn.hutool.core.util.IdUtil;
@@ -17,11 +17,11 @@ import com.alibaba.excel.write.metadata.WriteSheet;
 import com.alibaba.excel.write.metadata.fill.FillConfig;
 import com.alibaba.excel.write.metadata.fill.FillWrapper;
 import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
-import jakarta.servlet.ServletOutputStream;
-import jakarta.servlet.http.HttpServletResponse;
 import lombok.AccessLevel;
 import lombok.NoArgsConstructor;
 
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
@@ -255,7 +255,7 @@ public class ExcelUtil {
      */
     private static void resetResponse(String sheetName, HttpServletResponse response) {
         String filename = encodingFilename(sheetName);
-        FileUtils.setAttachmentResponseHeader(response, filename);
+        ServletUtils.setAttachmentResponseHeader(response, filename);
         response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
     }
 

+ 1 - 0
iot-common/iot-common-log/src/main/java/cc/iotkit/common/log/aspect/LogAspect.java

@@ -7,6 +7,7 @@ import cc.iotkit.common.satoken.utils.LoginHelper;
 import cc.iotkit.common.utils.JsonUtils;
 import cc.iotkit.common.utils.SpringUtils;
 import cc.iotkit.common.utils.StringUtils;
+import cc.iotkit.common.web.utils.ServletUtils;
 import cn.hutool.core.lang.Dict;
 import cn.hutool.core.map.MapUtil;
 import cn.hutool.core.util.ObjectUtil;

+ 0 - 3
iot-common/iot-common-log/src/main/java/cc/iotkit/common/log/event/LogininforEvent.java

@@ -4,7 +4,6 @@ import lombok.Data;
 
 import jakarta.servlet.http.HttpServletRequest;
 
-import java.io.Serial;
 import java.io.Serializable;
 
 /**
@@ -15,8 +14,6 @@ import java.io.Serializable;
 
 @Data
 public class LogininforEvent implements Serializable {
-
-    @Serial
     private static final long serialVersionUID = 1L;
 
     /**

+ 0 - 3
iot-common/iot-common-log/src/main/java/cc/iotkit/common/log/event/OperLogEvent.java

@@ -2,7 +2,6 @@ package cc.iotkit.common.log.event;
 
 import lombok.Data;
 
-import java.io.Serial;
 import java.io.Serializable;
 import java.util.Date;
 
@@ -14,8 +13,6 @@ import java.util.Date;
 
 @Data
 public class OperLogEvent implements Serializable {
-
-    @Serial
     private static final long serialVersionUID = 1L;
 
     /**

+ 35 - 20
iot-common/iot-common-oss/src/main/java/cc/iotkit/common/oss/core/OssClient.java

@@ -3,6 +3,8 @@ package cc.iotkit.common.oss.core;
 import cc.iotkit.common.oss.constant.OssConstant;
 import cc.iotkit.common.oss.exception.OssException;
 import cc.iotkit.common.oss.properties.OssProperties;
+import cc.iotkit.common.utils.DateUtils;
+import cc.iotkit.common.utils.StringUtils;
 import cn.hutool.core.io.IoUtil;
 import cn.hutool.core.util.IdUtil;
 import com.amazonaws.ClientConfiguration;
@@ -17,8 +19,6 @@ import com.amazonaws.services.s3.AmazonS3;
 import com.amazonaws.services.s3.AmazonS3Client;
 import com.amazonaws.services.s3.AmazonS3ClientBuilder;
 import com.amazonaws.services.s3.model.*;
-import org.dromara.common.core.utils.DateUtils;
-import org.dromara.common.core.utils.StringUtils;
 import cc.iotkit.common.oss.entity.UploadResult;
 import cc.iotkit.common.oss.enumd.AccessPolicyType;
 import cc.iotkit.common.oss.enumd.PolicyType;
@@ -47,7 +47,7 @@ public class OssClient {
         this.properties = ossProperties;
         try {
             AwsClientBuilder.EndpointConfiguration endpointConfig =
-                new AwsClientBuilder.EndpointConfiguration(properties.getEndpoint(), properties.getRegion());
+                    new AwsClientBuilder.EndpointConfiguration(properties.getEndpoint(), properties.getRegion());
 
             AWSCredentials credentials = new BasicAWSCredentials(properties.getAccessKey(), properties.getSecretKey());
             AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
@@ -58,10 +58,10 @@ public class OssClient {
                 clientConfig.setProtocol(Protocol.HTTP);
             }
             AmazonS3ClientBuilder build = AmazonS3Client.builder()
-                .withEndpointConfiguration(endpointConfig)
-                .withClientConfiguration(clientConfig)
-                .withCredentials(credentialsProvider)
-                .disableChunkedEncoding();
+                    .withEndpointConfiguration(endpointConfig)
+                    .withClientConfiguration(clientConfig)
+                    .withCredentials(credentialsProvider)
+                    .disableChunkedEncoding();
             if (!StringUtils.containsAny(properties.getEndpoint(), OssConstant.CLOUD_SERVICE)) {
                 // minio 使用https限制使用域名访问 需要此配置 站点填域名
                 build.enablePathStyleAccess();
@@ -191,9 +191,9 @@ public class OssClient {
      */
     public String getPrivateUrl(String objectKey, Integer second) {
         GeneratePresignedUrlRequest generatePresignedUrlRequest =
-            new GeneratePresignedUrlRequest(properties.getBucketName(), objectKey)
-                .withMethod(HttpMethod.GET)
-                .withExpiration(new Date(System.currentTimeMillis() + 1000L * second));
+                new GeneratePresignedUrlRequest(properties.getBucketName(), objectKey)
+                        .withMethod(HttpMethod.GET)
+                        .withExpiration(new Date(System.currentTimeMillis() + 1000L * second));
         URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
         return url.toString();
     }
@@ -215,13 +215,21 @@ public class OssClient {
     }
 
     private static String getPolicy(String bucketName, PolicyType policyType) {
+        String location = "";
+        switch (policyType) {
+            case WRITE:
+                location = "\"s3:GetBucketLocation\",\n\"s3:ListBucketMultipartUploads\"\n";
+                break;
+            case READ_WRITE:
+                location = "\"s3:GetBucketLocation\",\n\"s3:ListBucket\",\n\"s3:ListBucketMultipartUploads\"\n";
+                break;
+            default:
+                location = "\"s3:GetBucketLocation\"\n";
+        }
+
         StringBuilder builder = new StringBuilder();
         builder.append("{\n\"Statement\": [\n{\n\"Action\": [\n");
-        builder.append(switch (policyType) {
-            case WRITE -> "\"s3:GetBucketLocation\",\n\"s3:ListBucketMultipartUploads\"\n";
-            case READ_WRITE -> "\"s3:GetBucketLocation\",\n\"s3:ListBucket\",\n\"s3:ListBucketMultipartUploads\"\n";
-            default -> "\"s3:GetBucketLocation\"\n";
-        });
+        builder.append(location);
         builder.append("],\n\"Effect\": \"Allow\",\n\"Principal\": \"*\",\n\"Resource\": \"arn:aws:s3:::");
         builder.append(bucketName);
         builder.append("\"\n},\n");
@@ -230,12 +238,19 @@ public class OssClient {
             builder.append(bucketName);
             builder.append("\"\n},\n");
         }
+        String action = "";
+        switch (policyType) {
+            case WRITE:
+                action = "[\n\"s3:AbortMultipartUpload\",\n\"s3:DeleteObject\",\n\"s3:ListMultipartUploadParts\",\n\"s3:PutObject\"\n],\n";
+                break;
+            case READ_WRITE:
+                action = "[\n\"s3:AbortMultipartUpload\",\n\"s3:DeleteObject\",\n\"s3:GetObject\",\n\"s3:ListMultipartUploadParts\",\n\"s3:PutObject\"\n],\n";
+                break;
+            default:
+                action = "\"s3:GetObject\",\n";
+        }
         builder.append("{\n\"Action\": ");
-        builder.append(switch (policyType) {
-            case WRITE -> "[\n\"s3:AbortMultipartUpload\",\n\"s3:DeleteObject\",\n\"s3:ListMultipartUploadParts\",\n\"s3:PutObject\"\n],\n";
-            case READ_WRITE -> "[\n\"s3:AbortMultipartUpload\",\n\"s3:DeleteObject\",\n\"s3:GetObject\",\n\"s3:ListMultipartUploadParts\",\n\"s3:PutObject\"\n],\n";
-            default -> "\"s3:GetObject\",\n";
-        });
+        builder.append(action);
         builder.append("\"Effect\": \"Allow\",\n\"Principal\": \"*\",\n\"Resource\": \"arn:aws:s3:::");
         builder.append(bucketName);
         builder.append("/*\"\n}\n],\n\"Version\": \"2012-10-17\"\n}\n");

+ 24 - 0
iot-common/iot-common-web/src/main/java/cc/iotkit/common/web/utils/ServletUtils.java

@@ -191,4 +191,28 @@ public class ServletUtils {
         return URLDecoder.decode(str, StandardCharsets.UTF_8);
     }
 
+    /**
+     * 百分号编码工具方法
+     *
+     * @param s 需要百分号编码的字符串
+     * @return 百分号编码后的字符串
+     */
+    public static String percentEncode(String s) {
+        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8);
+        return encode.replaceAll("\\+", "%20");
+    }
+
+    /**
+     * 下载文件名重新编码
+     *
+     * @param response     响应对象
+     * @param realFileName 真实文件名
+     */
+    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) {
+        String percentEncodedFileName = percentEncode(realFileName);
+        String contentDispositionValue = String.format("attachment; filename=%s;filename*=utf-8''%s", percentEncodedFileName, percentEncodedFileName);
+        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
+        response.setHeader("Content-disposition", contentDispositionValue);
+        response.setHeader("download-filename", percentEncodedFileName);
+    }
 }

+ 1 - 1
iot-module/iot-system/src/main/java/cc/iotkit/system/controller/SysMenuController.java

@@ -7,7 +7,7 @@ import cc.iotkit.common.log.enums.BusinessType;
 import cc.iotkit.common.satoken.utils.LoginHelper;
 import cc.iotkit.common.utils.StringUtils;
 import cc.iotkit.common.web.core.BaseController;
-import cc.iotkit.system.dto.SysMenu;
+import cc.iotkit.model.system.SysMenu;
 import cc.iotkit.system.dto.bo.SysMenuBo;
 import cc.iotkit.system.dto.vo.MenuTreeSelectVo;
 import cc.iotkit.system.dto.vo.RouterVo;

+ 8 - 24
iot-module/iot-system/src/main/java/cc/iotkit/system/service/impl/SysOssServiceImpl.java

@@ -1,31 +1,29 @@
 package cc.iotkit.system.service.impl;
 
 import cc.iotkit.common.api.PageRequest;
-import cc.iotkit.common.constant.CacheNames;
 import cc.iotkit.common.api.Paging;
+import cc.iotkit.common.constant.CacheNames;
 import cc.iotkit.common.exception.BizException;
 import cc.iotkit.common.service.OssService;
 import cc.iotkit.common.utils.SpringUtils;
 import cc.iotkit.common.utils.StreamUtils;
 import cc.iotkit.common.utils.StringUtils;
-import cc.iotkit.common.utils.file.FileUtils;
 import cc.iotkit.model.system.SysOss;
 import cc.iotkit.system.dto.bo.SysOssBo;
 import cc.iotkit.system.dto.vo.SysOssVo;
+import cc.iotkit.system.service.ISysOssService;
 import cn.hutool.core.convert.Convert;
-import cn.hutool.core.io.IoUtil;
 import cn.hutool.core.util.ObjectUtil;
-import cc.iotkit.system.service.ISysOssService;
-import jakarta.servlet.http.HttpServletResponse;
 import lombok.RequiredArgsConstructor;
 import org.springframework.cache.annotation.Cacheable;
-import org.springframework.http.MediaType;
 import org.springframework.stereotype.Service;
 import org.springframework.web.multipart.MultipartFile;
 
 import java.io.IOException;
-import java.io.InputStream;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
 
 /**
  * 文件上传 服务层实现
@@ -92,21 +90,7 @@ public class SysOssServiceImpl implements ISysOssService, OssService {
     }
 
     @Override
-    public void download(Long ossId, HttpServletResponse response) throws IOException {
-        SysOssVo sysOss = SpringUtils.getAopProxy(this).getById(ossId);
-        if (ObjectUtil.isNull(sysOss)) {
-            throw new BizException("文件数据不存在!");
-        }
-        FileUtils.setAttachmentResponseHeader(response, sysOss.getOriginalName());
-        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE + "; charset=UTF-8");
-        OssClient storage = OssFactory.instance();
-        try(InputStream inputStream = storage.getObjectContent(sysOss.getUrl())) {
-            int available = inputStream.available();
-            IoUtil.copy(inputStream, response.getOutputStream(), available);
-            response.setContentLength(available);
-        } catch (Exception e) {
-            throw new BizException(e.getMessage());
-        }
+    public void download(Long ossId) throws IOException {
     }
 
     @Override
@@ -118,7 +102,7 @@ public class SysOssServiceImpl implements ISysOssService, OssService {
         try {
             uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
         } catch (IOException e) {
-            throw new ServiceException(e.getMessage());
+            throw new BizException(e.getMessage());
         }
         // 保存文件信息
         SysOss oss = new SysOss();